2015-02-23 28 views
0

我試圖解決這一運動從紅寶石僧網站,該網站說:紅寶石 - 計數每個單詞的重複在一個字符串

Try implementing a method called occurrences that accepts a string argument and uses inject 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 

回答

2

好吧,所以你的問題是,你是不是從塊返回正確的對象。 (在你的情況下,Hash

#inject是這樣的

[a,b] 
^ -> evaluate block 
|      | 
    -------return-------- V 

在您的解決方案,這是發生了什麼事

def occurrences(str) 
str.split.inject(Hash.new(0)) { |a, i| a[i] += 1 } 
end 
#first pass a = Hash.new(0) and i = word 
    #a['word'] = 0 + 1 
    #=> 1 
#second pass uses the result from the first as `a` so `a` is now an integer (1). 
#So instead of calling Hash#[] it is actually calling FixNum#[] 
#which requires an integer as this is a BitReference in FixNum.Thus the `TypeError` 

簡單的解決

def occurrences(str) 
str.split.inject(Hash.new(0)) { |a, i| a[i] += 1; a } 
end 
#first pass a = Hash.new(0) and i = word 
    #a['word'] = 0 + 1; a 
    #=> {"word" => 1} 

現在塊11返回Hash傳遞給再次。正如你所看到的解決方案返回塊的結尾處的對象build,因此該解決方案起作用。

+0

非常好的解釋。非常感謝您的努力。 – 2015-02-23 20:16:22