Using a variable as substitute for a method


#1

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.


#2

I think that Product["#{params[:foo]}"] should do the work.

Roland


#3

On 6/9/06, zero halo removed_email_address@domain.invalid 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]


#4

Alder G. 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.