Sort hashes using values

S

Subbu

Ruby automatically sorts hashes by keys, which means:
=> {"third"=>3, "second"=>1, "first"=>2}

How do I sort this by the values? So that I have:
{"second"=>1, "first"=>2, "third"=>3}
 
R

Rodrigo Bermejo

Subbu said:
Ruby automatically sorts hashes by keys, which means:

=> {"third"=>3, "second"=>1, "first"=>2}

How do I sort this by the values? So that I have:
{"second"=>1, "first"=>2, "third"=>3}

-------------> http://www.ruby-doc.org/core/classes/Hash.html
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]]
 
R

Robert Klemme

2008/3/10 said:
Subbu said:
Ruby automatically sorts hashes by keys, which means:

=> {"third"=>3, "second"=>1, "first"=>2}

How do I sort this by the values? So that I have:
{"second"=>1, "first"=>2, "third"=>3}


-------------> http://www.ruby-doc.org/core/classes/Hash.html
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
 
T

Todd Benson

Ruby automatically sorts hashes by keys, which means:

=> {"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
 
S

Subbu

Ruby automatically sorts hashes by keys, which means:
=> {"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

Thanks so much guys.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top