2013-05-01 56 views
0

我明白「count」方法的工作原理,從The string count() method計數如何在Ruby中工作

但我不明白它如何在陣列計算的話(而不是字母):

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")返回五,爲什麼不find_frequency("to be or not to be", "to")收益七(T,O,O,O, t,t,o)?

回答

2

根據所述documentationcount(p1)Array

返回元件的數量。如果給出了一個參數,則計算等於obj的元素數量。如果給出了一個塊,則計數產生真值的元素的數量。

在你的情況下,sentence.downcase.split給你["to", "be", "or", "not", "to", "be"]。在這裏,你有兩個數組元素等於"to",這就是爲什麼你獲得2

Stringdocumentationcount(*args)

每個other_str參數定義一組字符計數的。這些集合的交集定義了要在str中計數的字符。任何以脫字符(^)開頭的other_str都將被取消。序列c1-c2表示c1和c2之間的所有字符。

假如我們拋開否定的情況下,給定一個String參數p,呼籲count一個StringX返回X匹配p的字符中的一個字符數。

你的情況,你有"llool""hello world"匹配"lo",即5

+0

,謝謝!特別是鏈接到[apidock](http://apidock.com)。 – Evgeny 2013-05-01 07:57:23

+0

你可以加入這裏 - http://chat.stackoverflow.com/rooms/27184/ruby-conceptual? – 2013-05-01 10:29:25