From: "David A. Black" Date: 2009-07-20T05:57:44+09:00 Subject: Re: removing array duplicates where a subset is unique Hi -- On Mon, 20 Jul 2009, 7stud -- wrote: > Chuck Remes wrote: > >> (And Joel, I have presorted the array prior >> to removing the dupes so I have already taken care of the ordering >> issue.) > > That's well and good, but in the process of using a hash to remove the > duplicates, the result will be out of order. See example below. > > >> >> I was trying to figure out how to use a hash but did not >> make the leap to the ||= construction on my own. >> > > A simple if statement will achieve the same result: > > a = [ > [1, 2, 3, 10], > [1, 2, 3, 20], > [1, 2, 3, 30], > [2, 2, 3, 40] > ] > > h = {} > > a.each do |suba| > key = suba.slice(0, 3) > > if h[key] > next > else > h[key] = suba > end > > end > > p h.values > > --output:-- > [[2, 2, 3, 40], [1, 2, 3, 10]] I'm not sure what that buys you, though. The ||= idiom should work fine, unless you need to do something extra during the if statement. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN)