Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the behaviour of inject used with a lambda in Ruby

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?"

like image 661
Mike Berrow Avatar asked Sep 19 '08 14:09

Mike Berrow


1 Answers

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.

like image 187
rampion Avatar answered Nov 15 '22 05:11

rampion