views:

501

answers:

2

I often plug pre-configured lambdas into enumerable methods like 'map', 'select' etc. but the behavior of 'inject' seems to be different. e.g. with

mult4 = lambda {|item| item * 4 }

then

(5..10).map &mult4

gives me

[20, 24, 28, 32, 36, 40]

However, if I make a 2-parameter lambda for use with an inject like so,

multL = lambda {|product, n| product * n }

I want to be able to say

(5..10).inject(2) &multL

since 'inject' has an optional single parameter for the initial value, but that gives me ...

irb(main):027:0> (5..10).inject(2) &multL
LocalJumpError: no block given
        from (irb):27:in `inject'
        from (irb):27

However, if I stuff the '&multL' into a second parameter to inject, then it works.

irb(main):028:0> (5..10).inject(2, &multL)
=> 302400

My question is "why does that work and not the previous attempt?"

+7  A: 

So the reason that

(5..10).map &mult4

works and

(5..10).inject(2) &multL

doesn't is that ruby parens are implicit in the first case, so it really means

(5..10).map(&mult4)

if you wanted, for the second case you could use

(5..10).inject 2, &multL

The outside the parens trick only works for passing blocks to a method, not lambda objects.

rampion
A: 

I don't have an answer, but maybe an additional clue:

irb(main):001:0> (5..10).inject(2) { |product, n| product * n }
=> 302400

So if you hand it a block inline, it works? Very strange. Someone more experienced than me, please chime in.

Ben Hamill