7/8. Iterating over the hash

I have been trying to pass this exercise for a long time and am getting frustrated- I really need help. Here’s my code.

text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each { frequencies[word] += 1}

frequencies = frequencies.sort_by { |k, v| v }
frequencies.reverse!

frequencies.each do |word, frequency|
puts word + " " + frequency.to_s
end

Hello! I just passed this exercise being frustrated as well.

The code I used is as follows:

puts “Text:”
text = gets.chomp

words = text.split(" ")

frequencies = Hash.new(0)
words.each { |element| frequencies[element] += 1 }

frequencies = frequencies.sort_by {|a, b| b}
frequencies.reverse!

frequencies.each do |word, frequency|
puts word + " " + frequency.to_s
end

The only difference I can see between yours and mine is the line: words.each { frequencies[word] +=1}

Maybe try declaring a variable inside of words.each so you can add to the array like I do?

2 Likes

It still didn’t work but thanks anyway.

It worked when I left the editor blank. I think Codecademy has issues.

1 Like

This got me through but I don’t think it was really what they were asking for.

puts “How about a sentence?:”
text = gets.chomp

words = text.split(" ")

frequencies = Hash.new(0)
words.each { |word| frequencies[word] += 1 }

frequencies.each { |word,frequency| puts
word + " " +frequency.to_s}

What mean “.to_s”? My code was correct but it didn’t work till I wrote that. I don’t remember to read it in previous lessons, I’ve passed becouse I saw your comment so, thanks for that.

Here is my code (if it minds) ↓

puts "Enter your text here please: "
text = gets.chomp

words = text.split(" ")

frequencies = Hash.new(0)
words.each { |w| frequencies[w] += 1 }

frequencies.each { |w, f| puts w + " " + f.to_s }

It seemed to be the frequency.reverse! that made mine stick.

Once I took frequency.reverse! out, it worked perfectly, though laneeverhart is right, that’s not what codecademy asked or implied we should do.

Same here. It worries me that a website to teach programming has bugs in their code lol.

This works for me. Try this:

text = gets.chomp
puts text
words = text.split()

frequencies = Hash.new(0)

words.each do |word|
    puts frequencies[word] += 1
end
frequencies = frequencies.sort_by do |words, count| count end
frequencies.reverse!

frequencies.each do |word, count|
    puts "#{word} #{count}"
end

.to_s means “to string”.
The variable f in the above code is an integer, and you can’t concatenate integers to strings (i.e. you can’t stick numbers to strings). For example
puts "hello " + “world” <— prints “hello world”
puts "hello " + 5 <— doesn’t work because 5 is not a string
puts "hello " + “5” <— prints “hello 5”
puts "hello " + 5.to_s <— prints “hello 5” (first converts 5 to “5”, then concatenates)

1 Like

It would help if the example was actually related to what you were doing at the time… whoever designed this ruby unit is no teacher that’s for sure!