【发布时间】:2013-10-23 09:29:24
【问题描述】:
我想从 Ruby 代码块中的 yield 返回一个值。换句话说,我想将阻塞内部的值传递给块本身。
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 代码块中看到过这种行为。
【问题讨论】:
标签: ruby