Forum: Ruby on Rails using a variable as substitute for a method

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.
1b6ed15a6126e1d5ef4d7d15550f30bb?d=identicon&s=25 François Montel (zerohalo)
on 2006-06-09 19:56
That probably isn't the right title for this topic, but I'm not sure how
else to explain in succintly. I'm sorry if this is obvious but I
couldn't find the answer in the Ruby/Rails docs.

How do I use a variable as a substitute for a method/field, so that I
can call the object with the variable that contains the method name.

For example, say I have the object Product, that has methods Price,
Last_Price, Average_Price.

I want to be able to return the value of either of those three fields
based on the user selection. Ie, user selection is stored in
params[:foo], which I assign to variable field_to_show, and I want to be
able to call:

Product.field_to_show

which should output Product.Price (if params[:foo] contained 'Price')

Currently this gives a no method error.

I know that I can do
case params[:foo]
    when "Price"
         Product.Price
etc

but it seems to me that there should be a way of avoiding that extra
code.

I also tried:

Product.#{field_to_show}

and it didn't work (no method error)

Thansk for the help.
A0fdde9231afc79ff35cb186690d087c?d=identicon&s=25 Roland Mai (roland)
on 2006-06-09 20:00
I think that Product["#{params[:foo]}"] should do the work.

Roland
B780ee0ee1480454a85df58536702f63?d=identicon&s=25 Alder Green (Guest)
on 2006-06-09 20:04
(Received via mailing list)
On 6/9/06, zero halo <zerohalo@gmail.com> wrote:
> That probably isn't the right title for this topic, but I'm not sure how
> else to explain in succintly. I'm sorry if this is obvious but I
> couldn't find the answer in the Ruby/Rails docs.
>
> How do I use a variable as a substitute for a method/field, so that I
> can call the object with the variable that contains the method name.

Generally it's done by

obj.send(var)

Method calls are just messages send to objects, so you can use the
#send method to do that.

In ActiveRecords's case, there's a special convenience method that
should work:

ar_instance[var]
1b6ed15a6126e1d5ef4d7d15550f30bb?d=identicon&s=25 François Montel (zerohalo)
on 2006-06-09 20:12
Alder Green wrote:
> Generally it's done by
>
> obj.send(var)
>
> Method calls are just messages send to objects, so you can use the
> #send method to do that.
>
> In ActiveRecords's case, there's a special convenience method that
> should work:
>
> ar_instance[var]

Both of those worked. Thanks, Alder.
This topic is locked and can not be replied to.