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?"
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.
来源:https://stackoverflow.com/questions/102165/understanding-the-behaviour-of-inject-used-with-a-lambda-in-ruby