Afficher un message
Vieux 10/03/2008, 18h47   #2
Rodrigo Bermejo
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Sort hashes using values

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}


-------------> 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]]

--
Posted via http://www.ruby-forum.com/.

  Réponse avec citation
 
Page generated in 0,05127 seconds with 9 queries