FAQ: Create a Histogram - Sorting the Hash

This community-built FAQ covers the “Sorting the Hash” exercise from the lesson “Create a Histogram”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Ruby

FAQs on the exercise Sorting the Hash

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

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

I am really confused by this line of code, can someone please explain it to me. I get that you’re iterating over the words array but what does this part do:
frequencies[word] += 1

Any help would be appreciated :slight_smile:

1 Like

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

I believe all that this line of code is doing is increasing the counter that you initially set at ‘0’ (i.e. frequencies = Hash.new(0)).

As per the instructions on the 5th exercise: “This is why our default is 0 . The first time we find the word, it will have a default value of `` 0 that we can increment by 1`”

I’m not sure I understand the solution. Anyone willing to explain it in layman terms?

frequencies = frequencies.sort_by do |word, count|


As we enter this phase of the program, frequencies is a hash of words and their frequency. sort_by will return an array of word/count pairs, so no longer a hash. We choose which to sort by, word or count, and get a sorted list by that key. Since the hash is no longer needed, the output of this method is assigned back onto that variable.