What I want to do is name variables dynamically like:
def instance(instance)
@instance = instance #@instance isn't actually a variable called @instance, rather a variable called @whatever was passed as an argument
end
How can I do this?
What I want to do is name variables dynamically like:
def instance(instance)
@instance = instance #@instance isn't actually a variable called @instance, rather a variable called @whatever was passed as an argument
end
How can I do this?
Use instance_variable_set
.
varname = '@foo'
value = 'bar'
self.instance_variable_set varname, value
@foo # => "bar"
Or if you don't want the caller to have to supply the '@':
varname = 'foo'
value = 'bar'
self.instance_variable_set "@#{varname}", value
@foo # => "bar"
If I understand correctly you want to use "instance_variable_set":
class A
end
a = A.new
a.instance_variable_set("@whatever", "foo")
a.instance_variable_get("@whatever") #=> "foo"
You can't really.
You could play around with eval
, but really, it won't be readable.
Use the correct if
or use a hash instead.
# With Hash:
values = {}
a = :foo
values[a] = "bar"
values[:foo] # => "bar"
# With if
calc = "bar"
if a_is_foo
foo = calc
else
oof = calc
end
foo # => "bar"