I am trying to dynamically set (not create, it already has to exist) a global ruby variable in a method. The variable name is determined from the passed symbol. What I am currently doing is the following:
def baz(symbol)
eval("$#{symbol}_bar = 42")
end
$foo_bar = 0
baz(:foo)
puts $foo_bar # => 42
But to me, this kind of feels very wrong. Is this the way to do this? Or can it be done differently? Also, I don’t know how evals perform in ruby. Does it run much slower than
$foo_bar = 42
If you can use an instance variable instead, there is
Object#instance_variable_set.Note that it only accepts variable names that can be accepted as an instance variable (starting with
@). If you put anything else in the first argument, it will return an error. For the global variable counterpart to it, there is a discussion here: Forum: RubyEither way, you also have the problem of accessing the variable. How are you going to do that?