将块传递给方法-Ruby [英] Passing block into a method - Ruby
问题描述
我对传球有一点疑问.
def a_method(a, b)
a + yield(a, b)
end
这很好.
k = a_method(1, 2) do |x, y|
(x + y) * 3
end
puts k
但是这行不通.
puts a_method(1, 2) do |x, y|
(x + y) * 3
end
# LocalJumpError: no block given (yield)
有人可以对我解释一下吗?
Can anyone kindly explain this to me?
谢谢. Paolo Perrotta摘自元编程Ruby的示例.好书.
Thanks. Example taken from Metaprogramming Ruby by Paolo Perrotta. Great book.
推荐答案
do .. end
和花括号之间的区别在于,卷曲括号绑定到最右边的表达式,而
The difference between do .. end
and curly braces is that the curly braces bind to the rightmost expression, while do .. end
bind to the leftmost one. Observe the following examples:
def first(x=nil)
puts " first(#{x.inspect}): #{block_given? ? "GOT BLOCK" : "no block"}"
"f"
end
def second(x=nil)
puts " second(#{x.inspect}): #{block_given? ? "GOT BLOCK" : "no block"}"
"s"
end
first second do |x| :ok end # second(nil): no block
# first("s"): GOT BLOCK
first second {|x| :ok } # second(nil): GOT BLOCK
# first("s"): no block
在第一种情况下,用do..end
生成的块将绑定到第一个函数(最左侧).在第二种情况下,用大括号括起来的块将绑定到第二个函数(最右边).
In the first case, the block made with do..end
will be bound to the first function (leftmost). In the second case the block made with curly brackets will be bound to the second function (rightmost).
通常,如果您有两个功能和一个块,最好使用括号-只是为了便于阅读和避免错误.
Usually it's good idea to use parentheses if you have two functions and a block - just for readability and to avoid mistakes.
就像您的问题一样,很容易将一个块意外地传递给puts
方法.
It's very easy to accidentally pass a block to puts
method, just as in your question.
这篇关于将块传递给方法-Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!