On Sep 26, 10:56 am, Li Chen [email protected] wrote:
}.map(&:flatten)
- 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.
- 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.
-
#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]]