How to print a Ruby hash sorted by value

I recently needed to print the information in a Ruby hash, with the results sorted by value. Here's a general recipe on how to print the hash results sorted by value. I've created a sample hash, and populated the hash with sample data, to show how this works.

First, here's the sample code, using the first name of each person as the key, and the last name as the value of the key/value pair:

# an example of how to sort a Ruby hash by value.
# first, create the hash and populate it.
hash =
hash['al'] = 'alexander'
hash['barney'] = 'rubble'
hash['fred'] = 'flinstone'
hash['john'] = 'doe'

# sort the hash by value, and print the results in the sorted order.
hash.sort{|a,b| a[1]<=>b[1]}.each { |elem|
  puts "#{elem[1]}, #{elem[0]}"

Next, here are the results when this Ruby program is run, showing that the hash is indeed sorted by value (in this case the last name):

alexander, al
doe, john
flinstone, fred
rubble, barney


Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.