lundi 23 février 2015

Ruby - Count each word repetition in a string

I'm trying to solve this exercise from Ruby Monk website, which says:



Try implementing a method called occurrences that accepts a string argument and uses inject to build a Hash. The keys of this hash should be unique words from that string. The value of those keys should be the number of times this word appears in that string.



I've tried to do it like this:



def occurrences(str)
str.split.inject(Hash.new(0)) { |a, i| a[i] += 1 }
end


But I always get this error:



TypeError: no implicit conversion of String into Integer


Meanwhile, the solution for this one is quite the same (I think):



def occurrences(str)
str.scan(/\w+/).inject(Hash.new(0)) do |build, word|
build[word.downcase] +=1
build
end
end

Aucun commentaire:

Enregistrer un commentaire