On 2007-05-03 14:14:31 +0200, Josselin <josselin / wanadoo.fr> said:

> On 2007-05-03 14:06:44 +0200, Josselin <josselin / wanadoo.fr> said:
> 
>> given an array
>> 
>> anArray = [["a", 1, 1], ["b", 1, 2], ["c", 1, 5], ["z", 1, 1], ["e", 1, 
>> 5], ["f", 1, 6], ["g", 1, 1], ["h", 1, 3], ["i", 1, 1], ["j", 1, 2], 
>> ["k", 1, 1], ["y", 1, 6], ["m", 1, 1], ["u", 1, 2], ["v", 1, 1], ["p", 
>> 1, 4], ["q", 1, 5], ["r", 1, 1], ["n", 1, 1], ["t", 2, 3], ["s", 2, 2], 
>> ["o", 2, 1], ["w", 2, 1], ["x", 2, 1], ["l", 2, 1], ["d", 2, 1]]
>> 
>> I would like to get it  sliced in groups of element having the same 2nd 
>> and 3rd values
>> 
>> sliced_array = [
>> [ ["a", 1, 1],["g", 1, 1], ["i", 1, 1], ["k", 1, 1], ["m", 1, 1], ["n", 
>> 1, 1],["r", 1, 1],["v", 1, 1],["z", 1, 1] ],
>>  [ ["b", 1, 2],["j", 1, 2], ["u", 1, 2] ],
>> [ ["c", 1, 5],["e", 1, 5],["q", 1, 5] ],
>> [ ["d", 2, 1],["l", 2, 1], ["l", 2, 1], ["o", 2, 1],["w", 2, 1],["x", 2, 1] ],
>> [ ["f", 1, 6],["y", 1, 6] ],
>> [ ["h", 1, 3] ],
>> [ ["p", 1, 4] ],
>> [ ["s", 2, 2] ],
>> [ ["t", 2, 3] ]
>>  ]
>> 
>> I believe teh first step is to sort anArray.... then slicing similar 
>> groups, but writing
>>  anArray.sort {|a,b| a[1] <=> b[1]}
>> sorts only on first value... how can I sort on both.. ?
>> 
>> thansk
>> 
>> joss
> 
> found the sort... but how to slice it now ?
> anArray.sort_by {|item| [item[1], item[2] ] }
> => [["a", 1, 1], ["z", 1, 1], ["v", 1, 1], ["r", 1, 1], ["i", 1, 1], 
> ["m", 1, 1], ["g", 1, 1], ["k", 1, 1], ["n", 1, 1], ["j", 1, 2], ["u", 
> 1, 2], ["b", 1, 2], ["h", 1, 3], ["p", 1, 4], ["c", 1, 5], ["e", 1, 5], 
> ["q", 1, 5], ["f", 1, 6], ["y", 1, 6], ["l", 2, 1], ["x", 2, 1], ["o", 
> 2, 1], ["w", 2, 1], ["d", 2, 1], ["s", 2, 2], ["t", 2, 3]]
> 
> ["a", 1, 1], ["z", 1, 1], ["v", 1, 1], ["r", 1, 1], ["i", 1, 1], ["m", 
> 1, 1], ["g", 1, 1], ["k", 1, 1]
> ["j", 1, 2], ["u", 1, 2], ["b", 1, 2]
> and so on....
> 
> ???  thanks
> joss

found a reply from ... (thanks to him...)


module Enumerable
  def partition_by
    r = Hash.new{ |h,k| h[k]=[] }
    each do |e|
      r[ yield(e) ] << e
    end
    return r
  end
end

And then :

require 'enumerator'
sArray = anArray.sort_by {|item| [item[1], item[2] ] }

sArray.partition_by {|ary| ary[1..2]}.to_enum(:each_value).to_a=> 
[[["j", 1, 2], ["u", 1, 2], ["b", 1, 2]], [["l", 2, 1], ["x", 2, 1], 
["o", 2, 1], ["w", 2, 1], ["d", 2, 1]], [["a", 1, 1], ["z", 1, 1], 
["v", 1, 1], ["r", 1, 1], ["i", 1, 1], ["m", 1, 1], ["g", 1, 1], ["k", 
1, 1], ["n", 1, 1]], [["f", 1, 6], ["y", 1, 6]], [["t", 2, 3]], [["c", 
1, 5], ["e", 1, 5], ["q", 1, 5]], [["s", 2, 2]], [["p", 1, 4]], [["h", 
1, 3]]]

and that's it.....