了解在Ruby中与lambda一起使用的注入行为 [英] Understanding the behaviour of inject used with a lambda in Ruby
问题描述
我经常将预先配置的lambda插入到"map","select"等可枚举的方法中. 但是注入"的行为似乎有所不同. 例如与
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 }
然后
(5..10).map &mult4
给我
[20, 24, 28, 32, 36, 40]
但是,如果我制作一个2参数的lambda以便像这样进行注入,
However, if I make a 2-parameter lambda for use with an inject like so,
multL = lambda {|product, n| product * n }
我想说
(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
但是,如果我将'& multL'放入要插入的 second 参数中,那么它将起作用.
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?"
推荐答案
那是
(5..10).map &mult4
工作和
(5..10).inject(2) &multL
不是在第一种情况下,ruby parens是隐式的,所以确实意味着
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
parens技巧之外的方法仅适用于将块传递给方法,而不适用于lambda对象.
The outside the parens trick only works for passing blocks to a method, not lambda objects.
这篇关于了解在Ruby中与lambda一起使用的注入行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!