我真的很陌生ruby
。我创建了一个函数来计算字符串中单词的出现次数。但是,我一直在NoMethodError
努力+
。我搜索,尝试了不同的变体,但无法解决问题。这是代码:
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