From: Todd Benson Date: 2008-03-11T02:48:52+09:00 Subject: Re: Sort hashes using values On Mon, Mar 10, 2008 at 11:34 AM, Subbu wrote: > Ruby automatically sorts hashes by keys, which means: > > >> h = {"first"=>2,"second"=>1,"third"=>3} > => {"third"=>3, "second"=>1, "first"=>2} > > How do I sort this by the values? So that I have: > {"second"=>1, "first"=>2, "third"=>3} A hash, by nature, is not really sorted IIRC. If you sort, you need an Array object as a return value, which means using #sort_by... h = Hash["first", 2, "second", 1, "third", 3] h.sort_by {|k, v| v} It will give you an array of arrays. Todd