# Evaluating a variable from it's name

**URL:** <https://www.ruby-forum.com/t/evaluating-a-variable-from-its-name/110118>\
**Category:** Rails\
**Created:** [July 23, 2007, 2:25pm UTC](https://www.ruby-forum.com/t/evaluating-a-variable-from-its-name/110118 "2007-07-23T14:25:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rlorimor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/96bed5/32.png) [@rlorimor](https://www.ruby-forum.com/u/rlorimor)\
**Post date:** [July 23, 2007, 2:25pm UTC](https://www.ruby-forum.com/t/evaluating-a-variable-from-its-name/110118/1 "2007-07-23T14:25:21Z")

</div>

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…

---

<div class="post-metadata">

**Author:** ![rlorimor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/96bed5/32.png) [@rlorimor](https://www.ruby-forum.com/u/rlorimor)\
**Post date:** [July 23, 2007, 2:49pm UTC](https://www.ruby-forum.com/t/evaluating-a-variable-from-its-name/110118/2 "2007-07-23T14:49:32Z")

</div>

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](http://www.awprofessional.com/title/0321509242))  
RUBY FOR RAILS ([Ruby for Rails](http://www.manning.com/black))
- Ruby/Rails training  
& consulting: Ruby Power and Light, LLC ([http://www.rubypal.com](http://www.rubypal.com))

---

<div class="post-metadata">

**Author:** ![rlorimor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/96bed5/32.png) [@rlorimor](https://www.ruby-forum.com/u/rlorimor)\
**Post date:** [July 23, 2007, 3:24pm UTC](https://www.ruby-forum.com/t/evaluating-a-variable-from-its-name/110118/3 "2007-07-23T15:24:11Z")

</div>

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
