Sorting an Array of Hashes with Ruby and Enumerable

by Robby Russell

Disclaimer: This is my first post on the O'Reilly Ruby blog. I decided that I wanted to do my own Hello World... but decided that I'd just pick on our friend Enumerable and give you a quick 90 second tutorial. Start your watch... now.

Let's build an array of hashes



Let's take for example this nice array that we then populate with some hashes. In this case, a few of my co-workers and their current job titles.


argonistas = Array.new
argonistas << { :full_name => 'Allison Beckwith', :title => 'Creative Director' }
argonistas << { :full_name => 'Jeremy Voorhis', :title => 'Lead Architect' }
argonistas << { :full_name => 'Robby Russell', :title => 'Founder' }
argonistas << { :full_name => 'David Gibbons', :title => 'Lead Systems Adminstrator' }


This should be pretty straight-forward.

How do we #sort_by full name?



Okay, let's sort this array of hashes by the value of full_name in each hash. To do this, we can use #sort_by which comes with the Enumberable module.


argonistas.sort_by { |argonite| argonite[:full_name] }


Great. We have the ability to quickly sort the array of hashes.

Let's throw that array into a block



Let's take one step further and iterate through each hash in the array and output everyones full name and job title. What we can do is pass our array above to a block and print out these values.


argonistas.sort_by { |argonite| argonite[:full_name] }.each do |argonite|
puts "#{argonite[:full_name]}, #{argonite[:title]}"
end


Your STDOUT loves your hash keys



With this, we now get the following output:

Allison Beckwith, Creative Director
David Gibbons, Lead Systems Adminstrator
Jeremy Voorhis, Lead Architect
Robby Russell, Founder


It's Over!



As you can see, it doesn't take much to really embrace the power of Ruby without turning your code into an ugly mess.

1 Comments

Bruce D'Arcus
2005-12-21 09:40:56
Question: let's say my array data are unicode strings, and I need to properly sort extended characters. Can Ruby's sort_by handle that, and if so, how?


I couldn't get this to work correctly in casual playing with irb.