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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With