From: Rick DeNatale Date: 2009-09-27T00:23:38+09:00 Subject: Re: How to remove duplicate elements in a 2D array On Sat, Sep 26, 2009 at 10:56 AM, Li Chen wrote: > Thairuby ->a, b {a + b} wrote: >> The method ".map(&:flatten)" is use to converse hash back to array. > > > Thanks. > > But I still have some doubts about this line: > >  result = arr.inject({}){|x,y| x[y[0]]=y[1..-1]; >               x >              }.map(&:flatten) > > > 1) When I look at #inject method, I notice it only takes either no > augument or > an augument with initial value. But in your code it takes a hash. It is > kind of new/strange to me. It's giving it an empty hash as the initial value, nothing strange at all. > 2) Why do you  write an x alone after this line  x[y[0]]=y[1..-1]; ? So that the result of the block is the hash and not y[1..-1] which is the value of the assignment. > > 3) #map(&:flatten) doesn't work in my Ruby version(1.8.6). Which version > are you using? But I make some changes and it works. > > result = arr.inject( {  }  ){|x,y| x[y[0]]=y[1..-1]; x}.to_a > r=result.collect { |row| row.flatten} I'm guessing that he's using either 1.8.7 or 1.9 both of which define Symbol#to_proc which allows this, or perhaps he's using the activesupport gem which is part of Rails and defines this as well. I like David Black's alternative suggestion: result = arr.inject({}){|x,y| x[y[0]]=y; x}.values Note that neither of these preserve the ordering of the rows retained from the original array in Ruby 1.8.x, but if you're happy I guess that's not a requirement. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale