[英]Passing a proc as a block to a method
When I try to pass an arbitrary block to each_with_object
method, it raises an error: 当我尝试将任意块传递给each_with_object
方法时,会引发错误:
%w(foo bar baz).each_with_object([]) &->(i,m) { m << i.upcase }
# => NoMethodError: undefined method `&' for #<Enumerator: ["foo", "bar", "baz"]:each_with_object([])>
When I try to pass a block to inject
method, it also raise an error: 当我尝试将块传递给inject
方法时,它还会引发错误:
%w(foo bar baz).inject('') &->(m,i) { m + i.upcase }
# => NoMethodError: undefined method `' for "foo":String
But it works if I don't pass an initial value: 但是,如果我不传递初始值,它将起作用:
%w(foo bar baz).split.inject &->(m,i) { m + i.upcase }
And it also works when I pass a block to each
method. 当我向each
方法传递一个块时,它也起作用。
%w(foo bar baz).each &->(i) { puts i.upcase }
# FOO
# BAR
# BAZ
Can anyone explain this behaviour? 谁能解释这种行为? How can I pass arbitrary blocks to the first two examples? 如何将任意块传递给前两个示例?
The &
argument prefix turns an argument into the method's block (by calling to_proc
on it). &
参数前缀将参数转换为方法的块(通过在其上调用to_proc
)。 Since it's an argument, it must go inside the parens if you are using them, ie 因为这是一个参数,所以如果使用它们,它必须放在括号内,即
%w(foo bar baz).each_with_object([], &->(i,m) { m << i.upcase })
At the moment, ruby is interpreting the &
as the binary operator, and trying to do: 目前,ruby正在将&
解释为二进制运算符,并尝试执行以下操作:
(%w(foo bar baz).each_with_object([]) & (->(i,m) { m << i.upcase }))
Hence the error. 因此,错误。 I'm not sure why you're not just doing: 我不确定您为什么不这样做:
%w(foo bar baz).each_with_object([]) { |m,i| m << i.upcase }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.