# Accessing an instance variable by its name (as a string)

**URL:** <https://www.ruby-forum.com/t/accessing-an-instance-variable-by-its-name-as-a-string/54210>\
**Category:** Rails\
**Created:** [December 22, 2005, 6:20am UTC](https://www.ruby-forum.com/t/accessing-an-instance-variable-by-its-name-as-a-string/54210 "2005-12-22T06:20:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [December 22, 2005, 6:20am UTC](https://www.ruby-forum.com/t/accessing-an-instance-variable-by-its-name-as-a-string/54210/1 "2005-12-22T06:20:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [December 22, 2005, 6:28am UTC](https://www.ruby-forum.com/t/accessing-an-instance-variable-by-its-name-as-a-string/54210/2 "2005-12-22T06:28:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [December 22, 2005, 7:00am UTC](https://www.ruby-forum.com/t/accessing-an-instance-variable-by-its-name-as-a-string/54210/3 "2005-12-22T07:00:21Z")

</div>

Thanks a lot ! Worked a treat.
