A better example of the sort_by method for hashes in Ruby

August 4, 2016   

Codecademy is great for learning the fundamentals, but at the same time sometimes they use really confusing examples.

For example, in one of the lessons, you have to write code that looks like this:

puts “Enter Text:”
text = gets.chomp

words = text.split(“ ”)

frequencies = Hash.new(0)

words.each do |x| frequencies[x] += 1 end

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

What is this frequencies.sort_by { |k, v| v} code?!

It's actually really easy to understand if you look at another example of how the sort_by method is used in hashes.

First, what are hashes?

Hashes consist of keys and values. For example, we could have a people hash that contains information about a person's name and their age.

people = {
  :fred => 23,
  :joan => 18,
  :pete => 54
}

Inside the people hash, we have 3 sets of keys and values. :fred, :joan, :pete are all keys, and 23, 18, and 54 are all values.

Hashes are really nice because you can get the value of a key really quickly. For example, if we wanted to find out the age of :fred, all we have to do is this:

people[:fred]
# => 23

It's hard to do the same thing with arrays, so hashes are very useful.

However, what if we want to sort the hash? What if we want to sort the hash by the name or the age?

This is where the .sort_by method is handy :) Take a look at the code below:

people = {
  :fred => 23,
  :joan => 18,
  :pete => 54
}

people.sort_by { |name, age| age } # => [[:joan, 18], [:fred, 23], [:pete, 54]]

people.sort_by { |name, age| name } # => [[:fred, 23], [:joan, 18], [:pete, 54]]

people.sort_by { |name, age| age } -> here we are sorting the people hash by each person's age.

people.sort_by { |name, age| name } -> here we are sorting the people hash by each person's name.

By looking at this example, hopefully all of the sudden the mystery of frequencies.sort_by { |k, v| v} is solved :)

Originally posted in TECHRISE Community at www.techrise.me