我从The string count() method了解了“count”方法的工作原理。
但我不明白它是如何计算数组中的单词(而不是字母)的:
def find_frequency(sentence, word)
sentence.downcase.split.count(word.downcase)
end
find_frequency("to be or not to be", "to") # => 2
# same as ["to", "be", "or", "not", "to", "be"].count("to")
"hello world".count("lo") # => 5
如果"hello world".count("lo")
返回 5,为什么不find_frequency("to be or not to be", "to")
返回 7 (t, o, o, o, t, t, o)?