Newbie question: variable method call

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’).

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

elsif action == “pat”
pet.pat
#etc
end

I’d rather just do something like this:

pet.action

pet.send action

Cheers-
– Ezra Z.
– Lead Rails Evangelist
[email protected]
– Engine Y., Serious Rails Hosting
– (866) 518-YARD (9273)

Thanks Ezra!

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