How I can create/extract a variable/hash into the current binding in Ruby?
For instance, the following results in a NameError:
class Hash
def extract(b)
self.each do |key, value|
bind = b.eval <<-END
#{key} = nil
proc { |value| #{key} = value }
END
bind.call(value)
end
end
end
hash = {:a => 1}
hash.extract(binding)
puts a
Noteworthy mentioning, each call to Kernel#binding returns a different
Binding object instance, which makes me think that I’m not really changing
the binding of the caller of Hash#extract. For instance, the following
works:
class Hash
def extract(b)
self.each do |key, value|
bind = b.eval <<-END
#{key} = nil
proc { |value| #{key} = value }
END
bind.call(value)
end
end
end
hash = {:a => 1}
b = binding
hash.extract(b)
eval('puts a', b)
I’m unsure how make local variables appear within the execution context of the caller after the current binding has been passed to a method (e.g.,
#export_to, below). But something similar can be done that will superficially achieve the same effect:Note that
selfis being passed rather thanbinding.Also note that a common pattern here is to set instance variables rather than methods, in which case
putsand later code would now be able to reference@a.