块/lambda内部产生问题 [英] Trouble yielding inside a block/lambda
本文介绍了块/lambda内部产生问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下Ruby代码:
I have the following Ruby code:
# func1 generates a sequence of items derived from x
# func2 does something with the items generated by func1
def test(x, func1, func2)
func1.call(x) do | y |
func2.call(y)
end
end
func1 = lambda do | x |
for i in 1 .. 5
yield x * i
end
end
func2 = lambda do | y |
puts y
end
test(2, func1, func2) # Should print '2', '4', '6', '8', and '10'
这当然不起作用.
test.rb:11: no block given (LocalJumpError)
from test.rb:10:in `each'
from test.rb:10
from test.rb:4:in `call'
from test.rb:4:in `test'
from test.rb:20
推荐答案
Lambda不像常规方法那样隐式接受块,因此您的func1
无法屈服.改为执行此操作:
Lambdas don't implicitly accept blocks like regular methods do, so your func1
can't yield. Do this instead:
func1 = lambda do |x, &blk|
for i in 1 .. 5
blk.call(x * i)
end
end
具体来说,我认为这是因为yield会将控制权发送回caller
的块,其中不包括lambda调用.因此,以下代码就像您期望"一样工作:
Specifically, I believe this is because yield would send control back to the caller
's block, which would not include lambda invocations. So the following code works like you "expect":
def foo
(lambda { |n| yield(n) }).call(5)
end
foo { |f| puts f } # prints 5
这篇关于块/lambda内部产生问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文