0

我正在遍历一个对象图,并希望将一个块传递给它,该块将在一个方法的结构的每个节点上运行 - 我们称之为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}
4

3 回答 3

6

如果我理解正确,那么就像

second &block
于 2011-04-01T19:00:30.533 回答
1

如果您使用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}
于 2011-04-01T21:29:25.843 回答
0

只需调用 second 并将块变量(在本例中为 Proc)传递给它。

second block
于 2011-04-01T19:05:15.633 回答