Afficher un message
Vieux 11/03/2008, 08h09   #5
Subbu
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Sort hashes using values

On Mar 10, 10:48 am, Todd Benson <caduce...@gmail.com> wrote:
> On Mon, Mar 10, 2008 at 11:34 AM, Subbu <subramani.athiku...@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


Thanks so much guys.
  Réponse avec citation
 
Page generated in 0,04696 seconds with 9 queries