From: Josh Cheek Date: 2011-07-01T20:15:00+09:00 Subject: Re: How to order Structs based on two fields --bcaec54ee9206120a804a70020e7 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Fri, Jul 1, 2011 at 5:55 AM, I=F1aki Baz Castillo wrote: > 2011/7/1 I=F1aki Baz Castillo : > > I expected that the following could work: > > > > array.sort_by{|entry| entry.a or entry.b} > > > > but it generates: > > > > [kk1, kk2, kk3, kk4] > > > > so obviously it does not work. I'm not very used to Enumerable.sort_by > > method, any tip please? > > Maybe it would be better to use "class KK" rather than an struct, and > then define <=3D> method for KK class (and include Enumerable module)? > > -- > I=F1aki Baz Castillo > > > Structs return classes already (this is why you can inherit from them in th= e form `class A < Struct.new(:a,:b)`). You can pass Struct.new a block, and i= t will be evaluated within the context of the struct you are creating: KK =3D Struct.new(:a,:b) do def <=3D>(kk) if a < kk.a -1 elsif a > kk.a 1 else kk.b <=3D> b end end end kk1=3DKK.new(0,10) kk2=3DKK.new(0,5) kk3=3DKK.new(2,0) kk4 =3D KK.new(2,5) array =3D [kk3, kk2, kk1, kk4] # Elements with minor :a must be first. # If two elements have same :a, then order based on higher :b. # The result should be: [kk1, kk2, kk4, kk3] =3D=3D array.sort # =3D> true --bcaec54ee9206120a804a70020e7--