calling a method using a variable name??

A

ajtwatching

Hey folks,

Like many posts have no doubt started.. I'm giving this ruby business
a crack!! ;)

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.
 
T

Timothy Hunter

ajtwatching said:
Hey folks,

Like many posts have no doubt started.. I'm giving this ruby business
a crack!! ;)

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.
Look up the __send__ method:

obj.__send__("methodname", arg1, arg2)
 
K

KDr2

ajtwatching said:
Hey folks,

Like many posts have no doubt started.. I'm giving this ruby business
a crack!! ;)

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 }
methods.each{|m| friendly.send m}
 
R

Rick DeNatale

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

Giles Bowkett

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

Example from irb:
=> "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:
=> "muppet"

Badda bing badda boom.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top