The ramblings of Eric Seijo - Software Developer / Life Hacker

Ruby Haiku - Sorting an Array of Hashes

Posted by Eric Seijo Wed, 24 Feb 2010 15:38:00 GMT

 I'm constantly amazed at how easy it is to do (seemingly) complex tasks in Ruby.  I was recently faced with having to manipulate a large dataset for a report and give the user the ability to sort the data. Rather than deal with multiple queries to the database I queried once, grabbed what I needed and proceeded to manipulate the data and shove it in a data structure for use in display.  This being a Ruby on Rails site, I chose a Ruby array of hashes as the data structure.  

Example:

user_billing = [{:name=>"Eric", :location=>"Florida", :billing =>10000}, {:name=>"Adam", :location=>"North Carolina", :billing =>5000}]

Sort it based on name:

user_billing.sort_by { |billing| billing[:name] }

Result:

[{:billing=>5000, :location=>"North Carolina", :name=>"Adam"}, {:billing=>10000, :location=>"Florida", :name=>"Eric"}]

Now we can put it in a block:

user_billing.sort_by { |billing| billing[:name] }.each do |billing|
  puts "#{billing[:name]}, #{billing[:location]}, #{billing[:billing]}"
end

Displays:

Adam, North Carolina, 5000
Eric, Florida, 10000

Pretty cool and so simple.

Happy coding!