Sorting the hash


#1

https://www.codecademy.com/courses/learn-ruby/lessons/create-a-histogram/exercises/sorting-the-hash?action=lesson_resume&link_content_target=interstitial_undefined

I could figure out the correct code. I just want help understanding how this code asks to do a word count. is it the word ‘count’ itself? how does this code let the program know that we want to see the frequency of each word? also im having trouble understanding the purpose of { |word| frequencies[word] += 1 }

puts "what did yu do last night:"
text = gets.chomp

words = text.split

frequencies = Hash.new(0)

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

frequencies = frequencies.sort_by do |word, count|
  count
end

frequencies.reverse!



#2

Your each method accepts a block to do something with each element, and your sort_by accepts a block to tell it what to sort by. As for seeing the result, you’d want to puts out the result at the end, perhaps some extra code to format it.


#3

No, that word has no practical meaning other than to describe what the values are in the hash for each word key.

We must iterate over all the text to build up the hash with unique words. If your text phrase was longer, with more repeated words this would be evident.

frequencies = Hash.new(0)

The above invokes a new Hash instance with the directive to initialize each added key with the value of zero. We need that initial value so we can do math (addition). That’s where the next line comes in.

the rain in spain falls mainly in the plains

Split into an array,

['the', 'rain', 'in', 'spain', 'falls', 'mainly', 'in', 'the', 'plains']

The result of words.each will look like,

{
  'the' => 2,
  'rain' => 1,
  'in' => 2,
  'spain' => 1,
  'falls' => 1,
  'mainly' => 1,
  'plains' => 1
}
      ^       ^
    word    count

#4

so im assuming the that this line
words.each { |word| frequencies[word] += 1 }

finds the frequency of each word?


#5

Exactly.


#6

Thank you, i understand now :slight_smile:


#7

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