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.
B9f2cd54b3f85455af152162c2e5b1b2?d=identicon&s=25 Chris Hulbert (Guest)
on 2005-12-22 06: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")
Cee0292fffa691f1fb320d5400200e99?d=identicon&s=25 Marcel Molina Jr. (Guest)
on 2005-12-22 06:28
(Received via mailing list)
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
B9f2cd54b3f85455af152162c2e5b1b2?d=identicon&s=25 Chris Hulbert (Guest)
on 2005-12-22 07:00
Thanks a lot ! Worked a treat.
This topic is locked and can not be replied to.