Need help adding to hash

ruby

#1

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?


#2

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


#3

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


#4

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:


#5

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.


#6

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.