Sort hashes using values

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}

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}

-------------> class Hash - RDoc Documentation
hsh.sort => array
hsh.sort {| a, b | block } => array

Converts hsh to a nested array of [ key, value ] arrays and sorts it,
using Array#sort.

h = { “a” => 20, “b” => 30, “c” => 10 }
h.sort #=> [[“a”, 20], [“b”, 30], [“c”, 10]]
h.sort {|a,b| a[1]<=>b[1]} #=> [[“c”, 10], [“a”, 20], [“b”, 30]]

2008/3/10, Rodrigo B. [email protected]:

-------------> class Hash - RDoc Documentation
hsh.sort => array
hsh.sort {| a, b | block } => array

Converts hsh to a nested array of [ key, value ] arrays and sorts it,
using Array#sort.

h = { “a” => 20, “b” => 30, “c” => 10 }
h.sort #=> [[“a”, 20], [“b”, 30], [“c”, 10]]
h.sort {|a,b| a[1]<=>b[1]} #=> [[“c”, 10], [“a”, 20], [“b”, 30]]

and with #sort_by

irb(main):001:0> {“first”=>2,“second”=>1,“third”=>3}.sort_by {|k,v| v}
=> [[“second”, 1], [“first”, 2], [“third”, 3]]

Kind regards

robert

On Mon, Mar 10, 2008 at 11:34 AM, Subbu [email protected]
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

On Mar 10, 10:48 am, Todd B. [email protected] wrote:

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

Thanks so much guys.