I would like to return a value from a yield
in a Ruby code block. In other words, I would like to pass a value from inside the blocking into the block itself.
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"
What I would like to see for output is:
start
in block
doing other stuff
doing more stuff
done block 2
done
Is there any way to accomplish this without relying on the implicit return value at the end of a Ruby block? I believe this is possible, because I've seen this type of behavior in Sinatra
code blocks before.