From: pharrington Date: 2009-09-27T01:05:15+09:00 Subject: Re: How to remove duplicate elements in a 2D array On Sep 26, 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];ash. >                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. The argument passed to inject is the initial value. Thus, we just want the routine to start off with an empty hash. > 2) Why do you  write an x alone after this line  x[y[0]]=y[1..-1]; ? The value of the first argument to the block passed to inject is set to the return value of the block. In Ruby everything's an expression, so the return value of a method or block is just that of the last expression run. > 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. I don't have Ruby 1.8.6 installed and its been forever since I remember using it last, so (works in 1.8.7 and up though) :\ Also, here's a rather nasty version that retains the order of the initial array's elements, if that's important: irb(main):050:0> arry = [['a', 1, 2, 3], ['b', 4, 5, 6], ['c', 3, 2, 1], ['a', 1.3, 2.2, 3, 3], ['a', 2, 1, 3], ['a', 2.1, 1.5, 3]] => [["a", 1, 2, 3], ["b", 4, 5, 6], ["c", 3, 2, 1], ["a", 1.3, 2.2, 3, 3], ["a", 2, 1, 3], ["a", 2.1, 1.5, 3]] irb(main):051:0> arry.reverse.inject([]) {|r, e| r.unshift(e) if r.map {|x| x.first if x.first == e.first}.compact.size == 0; r} => [["b", 4, 5, 6], ["c", 3, 2, 1], ["a", 2.1, 1.5, 3]]