我感兴趣是否可以这样做以及语法是什么。我在:
def say_it
puts "before"
yield("something here")
puts "after"
end
say_it do |val|
puts "here is " + val
yield("other things") # ???
end
可能没有想到,但是如果块被转换为Proc?
事先提前答案 0 :(得分:5)
yield
仅在 中占用一个块的方法有意义。
是的,他们可以窝。请注意:
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