4

我对这是否可以完成以及语法是什么感兴趣。我在:

def say_it
  puts "before"
  yield("something here")
  puts "after"
end

say_it do |val|
  puts "here is " + val
  yield("other things") # ???
end 

认为可能没有,但也许如果块被转换为 Proc?

提前谢谢

4

1 回答 1

5

A仅采用块的方法中yield才有意义。

是的,它们可以筑巢。注意:

  1. 遍历仍然沿着堆栈发生;和
  2. 块(和yield)与方法严格相关。

例子:

def double(x)
    yield x * 2
end

def square_after_double(x)
    double(x) do |r|
       # Yields to the block given to the current method.
       # The location of the yield inside another block
       # does not change a thing.
       yield r * r
    end
end

square_after_double(3) do |r|
  puts "doubled and squared: " + r.to_s
end
于 2012-12-27T23:28:27.027 回答