是否可以在一个区块内调用收益率?

时间:2012-12-27 22:43:05

标签: ruby

我感兴趣是否可以这样做以及语法是什么。我在:

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

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

可能没有想到,但是如果块被转换为Proc?

事先提前

1 个答案:

答案 0 :(得分:5)

yield仅在 中占用一个块的方法有意义。

是的,他们可以窝。请注意:

  1. 遍历仍沿堆栈发生;和
  2. 块(和yield)严格依赖于方法。
  3. 示例:

    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