Understanding the behaviour of inject used with a lambda in Ruby

白昼怎懂夜的黑 提交于 2019-12-05 00:46:29

问题


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


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!