I’d like to write the method (define_variables) which can get a block and use the variables defined in it. Is it possible? For example, I’d like to get 5 in output:
module A
def self.define_variables
yield
puts a # not 5 :(
end
end
A::define_variables do
a = 5
end
Maybe there is some tricks with eval, but haven’t found anyone yet.
In short, no. After you’ve called
yieldthose 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, the5is still there in that it is returned by the block, and thusputs yieldwould print5. 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:Though I don’t know of anyway to
evalthe contents of a block. Regardless, in Ruby 1.9 the scope ofevalwas isolated and this will give you aNameError. You can do anevalwithin the context of aBindingthough: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.