我正在遍历一个对象图,并希望将一个块传递给它,该块将在一个方法的结构的每个节点上运行 - 我们称之为visit。
在顶部,我将使用一个块进行调用,并且我想将初始调用委托给访问根对象以访问其他对象。我可以使用 &last_parameter_name 将块解压缩到本地的 proc 中 - 但是如何在我的委托调用中将 proc 转回块?
这是一个简化的示例,我调用first(...)并希望将块委托给我对second(...)的调用
def second(&block) # ... ? ...
block.call(72)
end
def first(&block)
puts block.class # okay - now I have the Proc version
puts 'pre-doit'
block.call(42)
puts 'post-doit'
second( ... ? ...) # how do I pass the block through here?
end
first {|x| puts x*x}
注意:我需要在这里对 first() 和 second() 有相同的约定 - 即它们需要采用相同的东西。
阅读并尝试了答案后,我想出了一个更完整的工作示例:
class X
def visit(&x)
x.call(50)
end
end
class Y < X
def visit(&x)
x.call(100)
X.new.visit(&x)
end
end
Y.new.visit {|x| puts x*x}