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


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

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


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!!


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 }