[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Newbie question: variable method call

Kal Starkis

5/26/2007 5:51:00 AM

Is there a way to use the value of a variable to call a method of that
name?

For example, rather than use the following code to determine which
method of the 'pet' object to call:

if action == "feed"
pet.feed
elsif action == "walk"
pet.walk
elsif action == "pat"
pet.pat
#etc...
end


I'd rather just do something like this:

pet.action


The problem is, Ruby thinks I am trying to call a method named 'action',
instead of evaluating the variable and using its value (e.g. 'feed').

--
Posted via http://www.ruby-....

2 Answers

Ezra Zygmuntowicz

5/26/2007 5:58:00 AM

0


On May 25, 2007, at 10:50 PM, Kal Starkis wrote:

> Is there a way to use the value of a variable to call a method of that
> name?
>
> For example, rather than use the following code to determine which
> method of the 'pet' object to call:
>
> if action == "feed"
> pet.feed
> elsif action == "walk"
> pet.walk
> elsif action == "pat"
> pet.pat
> #etc...
> end
>
>
> I'd rather just do something like this:
>
> pet.action

pet.send action

Cheers-
-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- ez@engineyard.com
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)



Kal Starkis

5/26/2007 6:07:00 AM

0

Thanks Ezra!

--
Posted via http://www.ruby-....