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.