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

tim*_*one 4 ruby

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

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

say_it do |val|
  puts "here is " + val
  yield("other things") # ???
end 
Run Code Online (Sandbox Code Playgroud)

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

thx提前

小智 5

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
Run Code Online (Sandbox Code Playgroud)