In short, no. After you've called yield
those variables defined in the block are gone (sort of, as we shall see), except for what is returned—that's just how scope works. In your example, the 5
is still there in that it is returned by the block, and thus puts yield
would print 5
. Using this you could return a hash from the block {:a => 5}
, and then access multiple "variables" that way. In Ruby 1.8 (in IRb only) you can do:
eval "a = 5"
a # => 5
Though I don't know of anyway to eval
the contents of a block. Regardless, in Ruby 1.9 the scope of eval
was isolated and this will give you a NameError
. You can do an eval
within the context of a Binding
though:
def foo
b = yield
eval(a, b) + 2
end
foo do
a = 5
binding
end # => 7
It seems to me that what you're trying to do is emulate macros in Ruby, which is just not possible (at least not pure Ruby), and I discourage the use of any of the "workarounds" I've mentioned above.