Chris Hulbert
2005-Dec-22 05:20 UTC
Accessing an instance variable by its name (as a string)
Hi (again!) I have a function which gets passed the name of an instance variable, and spits its out all nicely formatted. Just wondering, how do i access the variable, when all i have is its name stored as a string? So far i''ve got this code, but it looks horrible. Is there a better way? eval("@" << inst_var_name << "." << field_name << ".to_s") -- Posted via http://www.ruby-forum.com/.
Marcel Molina Jr.
2005-Dec-22 05:33 UTC
Re: Accessing an instance variable by its name (as a string)
On Thu, Dec 22, 2005 at 06:20:47AM +0100, Chris Hulbert wrote:> Hi (again!) > I have a function which gets passed the name of an instance variable, > and spits its out all nicely formatted. > Just wondering, how do i access the variable, when all i have is its > name stored as a string? > > So far i''ve got this code, but it looks horrible. Is there a better way? > > eval("@" << inst_var_name << "." << field_name << ".to_s")>> @ivar = ''nine horses'' => "nine horses" >> name = ''ivar'' => "ivar" >> instance_variable_get("@#{name}") => "nine horses" >> field_name = ''size'' => "size" >> instance_variable_get("@#{name}").send field_name => 11 marcel -- Marcel Molina Jr. <marcel-WRrfy3IlpWYdnm+yROfE0A@public.gmane.org>