简体   繁体   中英

Take name of variable as input and output its value - Ruby

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"

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 

Yes, there is.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM