How to sort an array of hashes in ruby

jpw picture jpw · Mar 30, 2011 · Viewed 85.6k times · Source

I have an array, each of whose elements is a hash with three key/value pairs:

:phone => "2130001111", :zip => "12345", :city => "sometown"

I'd like to sort the data by zip so all the phones in the same area are together. Does Ruby have an easy way to do that? Can will_paginate paginate data in an array?

Answer

Gareth picture Gareth · Mar 30, 2011

Simples:

array_of_hashes.sort_by { |hsh| hsh[:zip] }

Note:

When using sort_by you need to assign the result to a new variable: array_of_hashes = array_of_hashes.sort_by{} otherwise you can use the "bang" method to modify in place: array_of_hashes.sort_by!{}