1

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

2 に答える 2

3

変化する

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

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

また

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"
于 2012-10-16T09:34:51.680 に答える
2

最初の反復では、h[x] は nil です。nil に 1 を追加しようとすると、エラーがスローされます。h[x] の初期値を 0 に設定すると、問題が解決します。

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

それ以外の

arr.each {|x| hash[x] += 1 }
于 2012-10-16T09:50:09.127 に答える