Iterating Over the Hash - undefined method?


#1

The code I have written is practically the same as the one, which allows you to pass the exercise. Even though, after I have typed in my phrase, I keep getting this error message: “undefined method `[]’ for nil:NilClass”

This is my code:

puts "Write a text to analyze"
text = gets.chomp
words = text.split
frequencies = Hash.new[0]
words.each do|word| frequencies[word] += 1
end
frequencies = frequencies.sort_by do |word, frequency|
frequency
end
frequencies.reverse!
frequencies.each do |word, frequency|
puts word + " " + frequency.to_s
end

What am I doing wrong, where is that wrong bit?
Thank you


#2

You have a typo at frequencies = Hash.new[0] line, it should be frequencies = Hash.new(0).

You can check the correct syntax on this link: class Hash.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.