将块传递到方法中-Ruby
我有一个关于传球的小问题将块传递到方法中-Ruby,ruby,block,Ruby,Block,我有一个关于传球的小问题 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) 谁能给我解释一下吗 谢谢。示例取自Paolo Perrotta的元编
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)
谁能给我解释一下吗
谢谢。示例取自Paolo Perrotta的元编程Ruby。好书。这是因为块被传递到
put
而不是a\u方法
这应该做到:
puts (a_method(1, 2) { |x, y| (x + y) * 3 })
# if you want to keep it multilines
puts (a_method(1, 2) { |x, y|
(x + y) * 3
})
这是因为块被传递到put
而不是a\u方法
这应该做到:
puts (a_method(1, 2) { |x, y| (x + y) * 3 })
# if you want to keep it multilines
puts (a_method(1, 2) { |x, y|
(x + y) * 3
})
do。。end
和花括号是指花括号绑定到最右边的表达式,而则绑定到最右边的表达式。。结束
绑定到最左边的一个。观察以下示例:
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
生成的块将绑定到第一个函数(最左边)。在第二种情况下,用花括号制作的块将绑定到第二个函数(最右边)
如果有两个函数和一个块,通常最好使用括号,这只是为了可读性和避免错误
很容易意外地将块传递给put
方法,就像您的问题一样。do之间的区别。。end
和花括号是指花括号绑定到最右边的表达式,而则绑定到最右边的表达式。。结束
绑定到最左边的一个。观察以下示例:
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
生成的块将绑定到第一个函数(最左边)。在第二种情况下,用花括号制作的块将绑定到第二个函数(最右边)
如果有两个函数和一个块,通常最好使用括号,这只是为了可读性和避免错误
很容易意外地将块传递给put
方法,就像你的问题一样。Hi,你能给我一个do..end的例子吗?在那之前我确实试过用花括号。我一直在想如何使用do..end。我一直在搜索,但没有找到关于这个问题的任何信息。也许,put
不只是应该在里面有一个do…end(这很有意义,因为它不应该显示多行内容)?即使对于多行块,您仍然可以继续使用大括号。嗨,您能给我举一个do..end的例子吗?在那之前我确实试过用花括号。我一直在想如何使用do..end。我一直在搜索,但没有找到关于这个问题的任何信息。也许,put
不只是应该在里面有一个do…end(这很有意义,因为它不应该显示多行内容)?即使对于多行块,也可以继续使用大括号。我明白了。谢谢你的解释!我懂了。谢谢你的解释!另请参见:、、、…、和。另请参见:、、…、和。