From: Erwin Date: 2008-06-01T15:34:33+09:00 Subject: Re: how to sort a multi-elements array On 31 mai, 19:40, Robert Klemme wrote: > On 31.05.2008 19:31, Erwin wrote: > > > I know how to sort an array with 2 elements... that's the only example > > I could fin on Array#sort... > > but what if ... I need to sort an array like this one : > > > anArray = [ [1, "joe", 4], [2, "arthur", 2], [5, "william", 3], [16, > > "bob", 1], [20, "ernesto", 17], [27, "julia", 1], [28, "barbara", 2] ] > > > sorting on third-element (highest ranking) , and second-element > > (nickname) > > > aSortedArray = [ [20, "ernesto", 17], [1, "joe", 4], 5, "william", 3], > > [2, "arthur", 2], [28, "barbara", 2], [16, "bob", 1] ] > > > any doc link where this is explained ? > > As always, use #sort with a block or #sort_by - the number of elements > in those arrays is irrelevant, you just need to decide which elements > you want to pick as sort key. > > an_array.sort_by {|a,b,c| [c,b]} > an_array.sort {|(a,b,c),(d,e,f)| [c,b] <=> [f,e]} > an_array.sort do |(a,b,c),(d,e,f)| > x = c <=> f > x == 0 ? b <=> e : x > end > > Btw, your data looks like it could benefit from using Struct and also > benefit from the automatically implemented <=>, i.e. > > Person = Struct.new :age, :name, :position > > an_array = [ > Person.new(4, "joe", 1), > Person.new(2, "arthur", 2), > Person.new(3, "william", 5), > ] > > Kind regards > > robert thanks Robert , I'll write that in my NoteTaker Ruby book !!