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

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

Thanks a lot ! Worked a treat.