Why do my hash values not increment with 1?


#1

https://www.codecademy.com/courses/learn-ruby/lessons/create-a-histogram/exercises/you-did-it?action=lesson_resume&link_content_target=interstitial_lesson

Hey everyone!

My code is working, or at least I’m not getting error messages, and it looks like I’m using the same code as everybody else. But when I print my hash, the hash values aren’t incremented. They are all equal to 1.

WHY IS THIS HAPPENING TO ME?!

Kidding, I’m not this desperate. I do like to know what I’m missing, thanks for your replies!

– Cor



puts "Tell me something!"
text = gets.chomp

words = text.split " "

frequencies = Hash.new(0)

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

frequencies = frequencies.sort_by { |words, count| count}

frequencies.reverse!

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



#2

You might want to look at the split Method…

https://stackoverflow.com/questions/1333347/how-to-split-a-string-in-ruby-and-get-all-items-except-the-first-one


#3

Hi Cor,

I have the same problem too! My code is accepted but my hash values aren’t incremented.

puts "please input here: "
text = gets.chomp

words = text.split(" ")

frequencies = Hash.new(0)

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

frequencies = frequencies.sort_by { |word, count|
count}

frequencies.reverse!

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

Have you figured out what has happened?

CWong


#4

I tried your code

puts "please input here: "
# text = gets.chomp
text="this this is a a a text"
words = text.split(" ")
puts words
frequencies = Hash.new(0)
puts frequencies
words.each { |altword|
  puts altword
 frequencies[altword] += 1 }
puts frequencies
frequencies = frequencies.sort_by { |word, count|
 count}

frequencies.reverse!

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

#5

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