11

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

1 Answer 1

16

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.