How to access an instance variable from my "string name"?

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

For example, I have an @my_var instance variable used in a class method. During the process, I can create the string "my_var" that tells me to change the @my_var instance variable.

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

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

Does anyone have a key?

thanks for the help

+8
metaprogramming instance-variables
source share
1 answer

Use instance_variable_set and instance_variable_get . Keep in mind that the line must have a leading @ :

 @foo = "bar" # => "bar" instance_variable_get("@foo") # => "bar" instance_variable_set("@foo", "baz") # => "baz" @foo # => "baz" 
+14
source share

All Articles