CREATE A HISTOGRAM Sorting the Hash


#1

<CREATE A HISTOGRAM Sorting the Hash - hanging ‘count’ >

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

Question: Code below works fine just really do not understand what the extra 'count ’ in the second frequencies array is doing.

I’m assuming it turns the count value in the array into an integer? Is it not already an integer?I’ve tried changing the name and keep breaking the code.

Is this convention explained / covered somewhere previously that I’ve missed? If so, a link to that lesson would be much appreciated.

See code below with #COMMENT where I am confused.

Cheers

```

puts "Enter a phrase you’d like to analyze: "
text = gets.chomp

words = text.split

frequencies = Hash.new(0)

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

frequencies = frequencies.sort_by do |word, count|
count #<== WHAT IS THIS count FOR?
end

frequencies.reverse!

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

<do not remove the three backticks above>

#2

Each hash item consists of a key (word) and a value (count). The sort_by method is given both objects, and sorts by count in ascending order. The lowest (word, count) pair will be at the top of the returned tuple array.

Example of reverse sorted array:

Enter some text: 
I AM SAM. I AM SAM. SAM I AM. THAT SAM-I-AM! THAT SAM-I-AM! I DO NOT LIKE THAT SAM-I-AM! DO WOULD YOU LIKE GREEN EGGS AND HAM? I DO NOT LIKE THEM,SAM-I-AM. I DO NOT LIKE GREEN EGGS AND HAM. WOULD YOU LIKE THEM HERE OR THERE? I WOULD NOT LIKE THEM HERE OR THERE. I WOULD NOT LIKE THEM ANYWHERE. I DO NOT LIKE GREEN EGGS AND HAM. I DO NOT LIKE THEM, SAM-I-AM. WOULD YOU LIKE THEM IN A HOUSE? WOULD YOU LIKE THEN WITH A MOUSE? I DO NOT LIKE THEM IN A HOUSE. I DO NOT LIKE THEM WITH A MOUSE. I DO NOT LIKE THEM HERE OR THERE. I DO NOT LIKE THEM ANYWHERE. I DO NOT LIKE GREEN EGGS AND HAM. I DO NOT LIKE THEM, SAM-I-AM.
LIKE 17
I 16
NOT 13
DO 12
THEM 8
WOULD 6
A 4
AND 4
EGGS 4
GREEN 4
YOU 4
OR 3
HERE 3
HAM. 3
SAM-I-AM! 3
THAT 3
WITH 2
IN 2
SAM-I-AM. 2
THEM, 2
ANYWHERE. 2
THERE. 2
SAM. 2
AM 2
MOUSE. 1
HOUSE. 1
MOUSE? 1
THEN 1
HOUSE? 1
THERE? 1
THEM,SAM-I-AM. 1
HAM? 1
AM. 1
SAM 1

Aside

A little more Rubyesque way to output text and data is with string interpolation:

frequencies.each {|k, v| puts "#{k} #{v}"}

#3

Thank you for this. Very helpful!


#4

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