Having this Error : undefined method `+' for nil:NilClass


#1

whats wrong with my code?
puts "Text Please"
text = gets.chomp

words = text.split {" "}
frequencies = Hash.new
words.each { |word| frequencies["word"] += 1 }


#2

The split() method uses (), not braces.

words = text.split(" ")

"word" itself is a string. In that case, you are always adding one to the key "word". So frequencies["word"], which maps the key "word" to a value gets incremented each time. The correct approach would be to use a variable; that is, remove the quotes!!

frequencies[word]

But there is also another problem with your code, like you are trying to add one to the current value of frequencies["word"], but there is nothing there! You created an empty hash, so there is nothing there. How could you add one to something that does not exist? :wink:

frequencies = Hash.new
words.each { |word| frequencies["word"] += 1 }