# Setting local variable from name

**URL:** <https://www.ruby-forum.com/t/setting-local-variable-from-name/114437>\
**Category:** Rails\
**Created:** [September 12, 2007, 6:28pm UTC](https://www.ruby-forum.com/t/setting-local-variable-from-name/114437 "2007-09-12T18:28:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mirek\_Rusin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/49beb7/32.png) [@Mirek\_Rusin](https://www.ruby-forum.com/u/Mirek_Rusin)\
**Post date:** [September 12, 2007, 6:28pm UTC](https://www.ruby-forum.com/t/setting-local-variable-from-name/114437/1 "2007-09-12T18:28:18Z")

</div>

Hi there!

How to set a local variable from a name inside a controller method?

In other words an equivalent to:

```
@my_object = MyObject.find(params[:id])

```

when I have only

```
name = "my_object"

```

How to set it as an local variable (with @ thingy)

```
??? = Object.const_get(name.classify).find(params[:id])

```

is there some kind of a method for the controller, something which  
looks similar to this:

```
set_local_object name,

```

Object.const\_get(name.classify).find(params[:id])  
^^^^^^^^^^^^^^^^  
?

Thanks,  
Mirek Rusin

---

<div class="post-metadata">

**Author:** ![Mirek\_Rusin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/49beb7/32.png) [@Mirek\_Rusin](https://www.ruby-forum.com/u/Mirek_Rusin)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/setting-local-variable-from-name/114437/2 "2007-09-17T13:24:02Z")

</div>

Hi Mirek,

I’m not sure if this is the best way, but it should work. You can  
construct  
the assignment in a string like this (where name = “my\_object”):

cmd = “@#{name} = #{name.classify}.find(params[:id])”

The value of cmd should then be “@my\_object =  
MyObject.find(params[:id])”.  
You can execute that string with the following:

eval(cmd)

If you want, you can compress it into one line. I broke it here out for  
simplicity’s sake.

-Dan
