Douglas
Douglas

Reputation: 5349

How to access instance variable from its "string name"?

Is there a way (meta programmation ?) to read/write an instance variable when we just know its string name ?

For instance I have a @my_var instance variable used within a class method. During the process, I will hapen to have a string "my_var" that tell me to change the @my_var instance variable.

Of course I could use a "if" statement, but I want it to be more dynamic as I will have potentially many different instance variables in my method.

I was thinking of something with "my_var".classify and something else...

Does anybody has a clue ?

Thanks for your help

Upvotes: 11

Views: 6832

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

Use instance_variable_set and instance_variable_get. Keep in mind the string needs to have the leading @:

@foo = "bar"
# => "bar"
instance_variable_get("@foo")
# => "bar"
instance_variable_set("@foo", "baz")
# => "baz"
@foo
# => "baz"

Upvotes: 16

Related Questions