Need help adding to hash

My code is this:
puts “What text would you like me to evaluate?”
text=gets.chomp
words=text.split
frequencies = Hash.new(0)
words.each
frequencies[words] += 1
I get a message saying frequencies isn’t set right. What is the problem?

Hi Nebulastar,

puts “Enter Statement, please”
text = gets.chomp

words = text.split

frequencies = Hash.new(0)

words.each { |word| frequencies[word] += 1}`

Is the correct code, just know that when you enter it, you “MUST” write some code into the text editor. Put your name, etc. and you should pass. I wracked my brain for almost a month, trying different codes and the problem was that, we were not told to input some type of code!!! `

2 Likes

Thank you for that! I was seriously stuck on that one step!

Hi @taleik,

Thanks for the help I was also stuck on that one but I’d like to run this code in a different way.
I’ve seen that words.each { |word| frequencies[word] += 1}` was working but what about this:

puts "Entrez le texte à analyser"
texte = gets.chomp
mots = texte.split
frequences = Hash.new (0)
mots.each do |x|
    x+=1
end

I’d like to use the mots.each do |x| but it doesn’t work, here is the error message I have:
can't convert Fixnum into String

Thanks for your time and help :slight_smile:

Hi @n7eonard

The problem here is that mots.each gives you access to each word in mots inside the block. So x is a word, and the code is trying to add 1 to x. This is like trying to do:

1 + "hello"

The solution is to use x as a key in the frequencies hash, and the value for that key is what you want to add 1 to:

puts "Entrez le texte à analyser"
texte = gets.chomp
mots = texte.split
frequences = Hash.new (0)
mots.each do |x|
    frequencies[x] +=1
end

I find that naming my variables more clearly helps make it clear in my mind what values I’m working with. So, instead of x, your variable name could be mot.

2 Likes

Wow thank you @liamseanbrady for this super quick answer, I’ve alwas been confused how to name my variables and now it’s pretty clear that I should systematically name if more clearly.