Afficher un message
Vieux 14/09/2007, 13h37   #2
Stefano Crocco
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Finding ties in sorting?

Alle venerd=EC 14 settembre 2007, Axel Etzold ha scritto:
> Dear all,
>
> I have many arrays like
>
> a=3D[{'a',10,'b',3},{'a',10,'b',4},{'a',5,'b',13},{'a', 13,'b',13},
> {'a',10,'b',7},{'a',5,'b',3}]
>
> which I'd like to sort such that I get the hashes with the highest
> values of 'a' first. If there are ties, I'd like to sort them (but not
> the entire array) such
> that the highest values of 'b' come first.
> So I can't just sort for 'a'-values first and then for 'b'-values,
> as this would destroy the first sort order.
>
> Is there a built-in way of getting the ties in sorting, such as an
> Array of the results of the <=3D> comparisons ?
>
> Thank you!
>
> Best regards,
>
> Axel


This should work:

a.sort_by{|i| [i['a'], i['b']]}.reverse

a.sort_by returns the hashes sorted by the values of 'a' and, in case of a=
=20
tie, the values of 'b', both in ascending order. Applying reverse to this=20
array gives you the correct order. The result is the following:

[{"a"=3D>13, "b"=3D>13}, {"a"=3D>10, "b"=3D>7}, {"a"=3D>10, "b"=3D>4}, {"a"=
=3D>10, "b"=3D>3},=20
{"a"=3D>5, "b"=3D>13}, {"a"=3D>5, "b"=3D>3}]

I hope this s

Stefano

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