私は で本当に新しい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