On Fri, Jul 1, 2011 at 4:22 PM, I=F1aki Baz Castillo <ibc / aliax.net> wrote:
> Hi, I've a struct like this:
>
> =A0KK =3D Struct.new(:a,:b)
>
> and some entries in an array:
>
> =A0kk1=3DKK.new(0,10)
> =A0#<struct KK a=3D0, b=3D10>
>
> =A0kk2=3DKK.new(0,5)
> =A0<struct KK a=3D0, b=3D5>
>
> =A0kk3=3DKK.new(2,0)
> =A0#<struct KK a=3D2, b=3D0>
>
> =A0kk4 =3D KK.new(2,5)
> =A0#<struct KK a=3D2, b=3D5>
>
> =A0array =3D [kk3, kk2, kk1, kk4]
>
>
> I need to order the array based:
> - Elements with minor :a must be first.
> - If two elements have same :a, then order based on higher :b.
>
> The result should be:
>
> =A0[kk1, kk2, kk4, kk3]
>
>
> I expected that the following could work:
>
> =A0array.sort_by{|entry| entry.a or entry.b}

How about:

array.sort do |i, j|
  r =3D i.a <=3D> j.a
  case r
    when 0 r
    else  -1 * (i.b <=3D> j.b)
  end
end


--=20
Anurag Priyam
http://about.me/yeban/