How to change the value of a variable which is a value in a hash (using the hash)?

Viewed 221

I have a hashtable that I'm using to store variables as values. I want to be able to change those variables by looking them up in the hash, but I can't think of a way to do this without changing the value itself.

bar = "ruby"
foo = {key: bar}
foo
#=> { "key" => "ruby" }

foo[:key] = "rails"
foo
#=> { "key" => "rails" }

How do I alter a variable stored as a value in a hash, instead of altering the hash itself?

1 Answers

I wonder why you would want to do such a thing, but you could store the names of the variables instead of the variables themselves:

bar = "ruby"
foo = {key: 'bar'}

Setting a variable:

eval("#{foo[:key]} = 'rails'")
p foo # {:key=>"bar"}
p bar # "rails"

Getting a variable:

eval(foo[:key])
Related