Setting local variable from name

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,


Mirek Rusin

Hi Mirek,

I’m not sure if this is the best way, but it should work. You can
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 =
You can execute that string with the following:


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


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs