Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 775
Douglas Avatar asked Jan 07 '13 13:01

Douglas


1 Answers

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"
like image 59
Dylan Markow Avatar answered Oct 15 '22 22:10

Dylan Markow