Calling a method using a variable name?

Hey folks,

Like many posts have no doubt started… I’m giving this ruby business
a crack!! :wink:

Now this might be a really bad approach… but I’ll throw it out there.

Here’s my simple class.

class Myclass
def initialize
end

def hello
puts “hello”
end

def bye
puts “bye”
end
end

As expected, works a treat.

friendly = Myclass.new
friendly.hello
friendly.bye

Now, given I now what methods are available, is there a way to do
something similar to this…

methods = [‘hello’, ‘bye’]
methods.each { |m| friendly.m }

Regards,

ajt.

ajtwatching wrote:

def initialize

methods.each { |m| friendly.m }

Regards,

ajt.

Look up the send method:

obj.send(“methodname”, arg1, arg2)

“ajtwatching” [email protected] writes:

def initialize

methods.each { |m| friendly.m }
methods.each{|m| friendly.send m}

Regards,

ajt.


http://kdr2.net

                                           ------yours Killy Draw

On 3/13/07, Timothy H. [email protected] wrote:

Look up the send method:

obj.send(“methodname”, arg1, arg2)

Or just send which in most cases is preferable. They both do the same
thing (in fact I believe that one is an alias of the other). send
is there to cover cases where a class defines a send method for
another purpose.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Yep, +1. Use #send() rather than #send().

Example from irb:

“muppet”.send(:to_s)
=> “muppet”

You’re telling the String object “muppet” to receive the message
“to_s”, in a Smalltalk sense, or, in a Java sense, you’re telling the
String object “muppet” to call the method “to_s”.

To do it with a variable:

kermit = “to_s”
=> “to_s”
“muppet”.send(kermit)
=> “muppet”

Badda bing badda boom.


Giles B.
http://www.gilesgoatboy.org

http://giles.tumblr.com/