Accessing an instance variable by its name (as a string)


#1

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”)


#2

On Thu, Dec 22, 2005 at 06:20:47AM +0100, Chris H. 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


#3

Thanks a lot ! Worked a treat.