juwiley juwiley - 7 months ago 27
Ruby Question

Dynamically set local variables in Ruby

I'm interested in dynamically setting local variables in Ruby. Not creating methods, constants, or instance variables.

So something like:

args[:a] = 1
args.each_pair do |k,v|
Object.make_instance_var k,v
end
puts a
> 1


I want locally variables specifically because the method in question lives in a model and I dont want to pollute the global or object space.

Answer

The problem here is that the block inside each_pair has a different scope. Any local variables assigned therein will only be accessible therein. For instance, this:

args = {}
args[:a] = 1
args[:b] = 2

args.each_pair do |k,v|
  key = k.to_s
  eval('key = v')
  eval('puts key')
end

puts a

Produces this:

1
2
undefined local variable or method `a' for main:Object (NameError)

In order to get around this, you could create a local hash, assign keys to this hash, and access them there, like so:

args = {}
args[:a] = 1
args[:b] = 2

localHash = {}
args.each_pair do |k,v|
  key = k.to_s
  localHash[key] = v
end

puts localHash['a']
puts localHash['b']

Of course, in this example, it's merely copying the original hash with strings for keys. I'm assuming that the actual use-case, though, is more complex.

Comments