计数如何在Ruby中工作

时间:2013-05-01 07:11:43

标签: ruby arrays count

我从The string count() method了解“计数”方法的工作原理。

但我无法理解它是如何计算数组中的单词(而不是字母):

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)?

1 个答案:

答案 0 :(得分:2)

根据documentationcount(p1) Array

  

返回元素数量。如果给出参数,则计算等于obj的元素数。如果给出了一个块,则计算产生真值的元素数。

在您的情况下,sentence.downcase.split会为您提供["to", "be", "or", "not", "to", "be"]。在这里,您有两个等于"to"的数组元素,这就是您获得2的原因。

来自String的{​​{3}},count(*args)

  

每个other_str参数定义要计数的一组字符。这些集合的交集定义了要在str中计数的字符。任何以插入符号(^)开头的other_str都将被否定。序列c1-c2表示c1和c2之间的所有字符。

如果我们放弃否定案例,给定String参数 p ,请在count x 上致电String x 中的字符数与 p 中的一个字符匹配。

在您的情况下,您"llool" "hello world"匹配"lo"5