From: Rob Biedenharn Date: 2011-07-01T21:24:23+09:00 Subject: Re: How to order Structs based on two fields On Jul 1, 2011, at 7:18 AM, Robert Klemme wrote: > On Fri, Jul 1, 2011 at 12:55 PM, Iņaki Baz Castillo > wrote: >> 2011/7/1 Iņaki 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 <=> method for KK class (and include Enumerable module)? > > You can do > > array.sort_by {|e| [e.a, e.b]} > > But you can of course define <=> for a Struct class as well > > KK = Struct.new :a,:b do > include Comparable > > def <=>(o) > cmp = a <=> o.a > cmp == 0 ? b <=> o.b : cmp > end > end Actually, there's a method to help with exactly this sort of thing (pun intended). def <=>(o) (a <=> o.a).nonzero? || b <=> o.b end Take a look at Numeric#nonzero? and you'll find an example that's almost exactly this. -Rob > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ > Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/