Afficher un message
Vieux 10/03/2008, 19h48   #4
Todd Benson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Sort hashes using values

On Mon, Mar 10, 2008 at 11:34 AM, Subbu <subramani.athikunte@gmail.com> 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

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