0
我試圖解決這一運動從紅寶石僧網站,該網站說:紅寶石 - 計數每個單詞的重複在一個字符串
Try implementing a method called
occurrences
that accepts a string argument and usesinject
to build a Hash. The keys of this hash should be unique words from that string. The value of those keys should be the number of times this word appears in that string.
我一直試圖做這樣的:
def occurrences(str)
str.split.inject(Hash.new(0)) { |a, i| a[i] += 1 }
end
但我總是得到這樣的錯誤:
TypeError: no implicit conversion of String into Integer
同時,該解決方案FO這一點是相當相同的(我認爲):
def occurrences(str)
str.scan(/\w+/).inject(Hash.new(0)) do |build, word|
build[word.downcase] +=1
build
end
end
非常好的解釋。非常感謝您的努力。 – 2015-02-23 20:16:22