Forum: Ruby on Rails Accessing an instance variable by its name (as a string)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris H. (Guest)
on 2005-12-22 07:20
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")
Marcel Molina Jr. (Guest)
on 2005-12-22 07:28
(Received via mailing list)
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
Chris H. (Guest)
on 2005-12-22 08:00
Thanks a lot ! Worked a treat.
This topic is locked and can not be replied to.