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
'散列[X] = 1'用於第一發生? – halfelf
我的嘗試的問題是增加'hash [x]'的值,但是當第一個項目迭代時沒有值。對? – mert
是的,您可以使用'hash = Hash.new(0)'設置默認值'0' – Salil