From: Kristof Bastiaensen Date: 2004-08-16T22:11:13+09:00 Subject: Re: returning symbols Hi, On Mon, 16 Aug 2004 21:47:59 +0900, Daniel Cremer wrote: > I want to write a method to store a list of some instance variables in an > Array that will later be run through to access their data. Normally in > another language I would do this by passing them by reference when I store > them into the Array. > > Using the object_id doesn't work because that's to the object the variable > is pointing to and this may change. So, to sum it up: > > Is there a way to get variables to return their symbol so you can access > what they will be referencing in the future ? > > thanks, > Daniel You can use the name as a string or symbol, and retrieve the value with instance_variable_get. > ri instance_variable_get ------------------------------------------- Object#instance_variable_get obj.instance_variable_get(symbol) => obj ------------------------------------------------------------------------ Returns the value of the given instance variable (or throws a NameError exception). The @ part of the variable name should be included for regular instance variables 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 Cheers, KB