From: Daniel Finnie Date: 2008-01-08T02:53:37+09:00 Subject: Re: compact or uniq that takes a block like sort? A more general solution: require 'set' class Array def uniq(&blk) blk ||= lambda {|x| x} already_seen = Set.new uniq_array = [] self.each_with_index do |value, i| x = blk.call(value) unless already_seen.include? x already_seen << x uniq_array << value end end uniq_array end end and class Array def consolidate reverse.uniq {|a| a.first}.reverse end end Of course, the value that you keep for uniq is kinda arbitrary. Dan - Hide quoted text - On 1/7/08, Joel VanderWerf wrote: > Pit Capitain wrote: > > 2008/1/7, Bil Kleb : > >> I'm looking for an elegant way to do the following: > >> (...) > > > > Bil, this makes the test pass: > > > > class Array > > def consolidate > > Hash[*flatten].sort > > end > > end > > That certainly is elegant! > > Maybe Bil wanted to preserve the monotonicity? > > class Array > def consolidate > Hash[*flatten].sort_by {|x,y| y} > end > end > > p [ [5,1] , [3,2] ].consolidate # ==> [[5, 1], [3, 2]] > > -- > vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407 > >