Forum: Ruby on Rails Evaluating a variable from it's name

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.
B199c6556fec872d272086be15c5e4ab?d=identicon&s=25 Robert La ferla (rlaferla)
on 2007-07-23 14:25
(Received via mailing list)
If I have a string variable that contains the "name" of another
variable.  How can I access that other variable for both assignment
and evaluation?

e.g.

x = 100
nameofvar = "x"

I want to set the value of the variable specified by nameofvar and
also get it's value.

Seems like some sort of reflection calls would be needed for this...
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-07-23 14:49
(Received via mailing list)
Hi --

On Mon, 23 Jul 2007, rlaferla wrote:

> I want to set the value of the variable specified by nameofvar and
> also get it's value.
>
> Seems like some sort of reflection calls would be needed for this...

There's eval, but in almost seven years of Ruby program I have never
needed to do that, and would be very surprised if it were really a
good idea.  Anyway, that wasn't your question, so I'll leave it at
that :-)


David

--
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)
0fe01b8879c35beee8c9b2e9212a5b87?d=identicon&s=25 jeroen.knoops@gmail.com (Guest)
on 2007-07-23 15:24
(Received via mailing list)
Hello,

See the following code:

class Reflection
   attr_accessor :x
   def y
     "y"
   end
   def call_method (method_name)
      self.send(method_name)
   end
end

Now you can do the following things:

>> r = Reflection.new
=> #<Reflection:0xb7172b60>
>> r.call_method("y")
=> "y"
>> r.call_method("x")
=> nil
>> r.x = "test"
=> "test"
>> r.call_method("x")
=> "test"
>>

Best regards,
Jeroen
This topic is locked and can not be replied to.