0

I'd like to know if there is something Ruby that does something like this:

@my_var = "foo"
some_function_i_dont_know_name_of("@my_var")
 => "foo"
3
  • eval("@my_var") would also do. Commented May 23, 2019 at 13:51
  • 1
    eval could potentially be used for code injections, if the value of @my_var can be set from the outside. instance_variable_get is safer. Commented May 23, 2019 at 13:55
  • 1
    eval is evil. Commented May 23, 2019 at 15:40

2 Answers 2

5

Seems like you are looking for instance_variable_get. From the docs:

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name. String arguments are converted to symbols.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a)    #=> "cat"
fred.instance_variable_get("@b")   #=> 99
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, there is.

@my_var = "foo"
instance_variable_get("@my_var")
 => "foo"

Comments

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.