我想从yield
Ruby 代码块中的 a 返回一个值。换句话说,我想将一个值从阻塞内部传递到块本身。
def bar
puts "in block"
foo = 1
# The next line is wrong,
# but this is just to show that I want to assign a value to foo
foo = yield(foo)
puts "done block #{foo}"
end
puts "start"
bar do |shoop|
puts "doing other stuff"
shoop = 2
puts "doing more stuff"
# The following commented-out line would work,
# but I would rather not force the programmer
# to always put a variable at the end
#shoop
end
puts "done"
我希望看到的输出是:
start
in block
doing other stuff
doing more stuff
done block 2
done
有什么方法可以在不依赖 Ruby 块末尾的隐式返回值的情况下实现这一点?Sinatra
我相信这是可能的,因为我以前在代码块中看到过这种行为。