如何委托通过随附的块进行调用?

我正在遍历一个对象图,并希望传递一个块,该块将从一个方法运行在结构的每个节点上 - 让我们称之为访问。 在顶部,我将调用一个块,我想委托初始调用访问根对象以访问其他对象。我可以使用& last_parameter_name将块解压缩到本地proc中 - 但是如何在我委托的调用中将proc转回块? 这是一个简化的例子,我先调用(...)并希望将块委托给我的第二个调用(...)
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}
    
已邀请:
如果我理解正确,那么就像
second &block
    
如果使用yield,则并不总是需要显式传递块。
def first( &block )
  puts block.class     # okay - now I have the Proc version
  puts 'pre-doit'
  yield 42
  puts 'post-doit'
  second( &block ) #the only reason the &block argument is needed. yield 42 can do without.
end

def second #no block argument here, works all the same 
  yield 72
end

first {|x| puts x*x}
    
只需调用第二个并传递块变量(在本例中为Proc)。
second block
    

要回复问题请先登录注册