2012-10-16 30 views
1

我真的很新,在ruby。我創建了一個函數來計算字符串中單詞的出現次數。不過,我一直在得到NoMethodError。我搜索,嘗試了不同的變化,但無法解決問題。下面是代碼:NoMethodError for ruby​​加號

def count_words(str) 
    str_down = str.downcase 
    arr = str_down.scan(/([\w]+)/).flatten 
    hash = Hash[] 
    arr.each {|x| hash[x] += 1 } 
    (hash.sort_by {|key, value| value}.reverse) 
end 

以下是錯誤:

NoMethodError: undefined method `+' for nil:NilClass 
    from ./***.rb:14:in `count_words' 
    from ./***.rb:14:in `each' 
    from ./***.rb:14:in `count_words' 
    from (irb):137 

回答

3

變化

hash = Hash[] 
arr.each {|x| hash[x] += 1 } 

hash = {} 
arr.each {|x| hash[x] =0 unless hash[x]; hash[x] += 1 } 

OR

hash = Hash.new(0) 
arr.each {|x| hash[x] += 1 } 

闡釋

hash = {} 
hash[1] = "example1" #ASSIGNMENT gives hash = {1: "example1"} 
p hash[2] #This gives `nil` by default, as key is not present in hash 

爲了給默認值,其不存在於哈希密鑰,我們必須進行以下操作:

hash = Hash.new("new value") 
    p hash #Gives {} 
    p hash[4] #gives "new value" 
+0

'散列[X] = 1'用於第一發生? – halfelf

+0

我的嘗試的問題是增加'hash [x]'的值,但是當第一個項目迭代時沒有值。對? – mert

+0

是的,您可以使用'hash = Hash.new(0)'設置默認值'0' – Salil

2

在第一次迭代中,h [x]表示零。試圖添加1到零拋出錯誤。將h [x]的初始值設置爲0將解決該問題。

arr.each {|x| hash[x]||=0; hash[x] += 1 } 

代替

arr.each {|x| hash[x] += 1 }