Ruby 中的块与枚举:深入探索
在 Ruby 编程中,块与枚举是极为强大且有趣的特性,它们能让代码更加简洁、灵活和高效。下面将详细探讨这些特性及其应用。
1. 词频统计示例
在早期,我们可能会自定义 count_frequency 方法来统计词频,还会编写一系列测试用例来验证其功能,例如:
def test_single_word
assert_equal({"cat" => 1}, count_frequency(["cat"]))
end
def test_two_different_words
assert_equal({"cat" => 1, "sat" => 1}, count_frequency(["cat", "sat"]))
end
# 其他测试用例...
不过,随着 Ruby 标准库的发展, Array 类现在有了 tally 方法,它能实现和 count_frequency 相同的功能。下面是一个使用 tally 方法进行词频统计的示例:
require_relative "words_from_string"
raw_text = "The problem breaks down into two parts. First, given some text as a string, return a list o
超级会员免费看
订阅专栏 解锁全文
317

被折叠的 条评论
为什么被折叠?



