method by string ?

R

Roeland Moors

I'm creating a program which uses a ruby source file as config
file.

I don't know which methods are defined in this config file.

The problem I have is that I would like to run a method with the same
name as a string.

Example:
This is the config file

class Main
def test1
puts 'test1'
end

def test2
puts 'test2'
end
end


This is the main source:

$method = "test1"
$mode = Main.new

# this ofcours doesn't work:
$mode.$method

How should I do this?
 
T

ts

R> $mode.$method

$mode.send($method) # ruby will be able to call also private and
# protected methods



Guy Decoux
 
R

Roeland Moors

I'm creating a program which uses a ruby source file as config
file.

I don't know which methods are defined in this config file.

The problem I have is that I would like to run a method with the same
name as a string.

Example:
This is the config file

class Main
def test1
puts 'test1'
end

def test2
puts 'test2'
end
end


This is the main source:

$method = "test1"
$mode = Main.new

# this ofcours doesn't work:
$mode.$method

How should I do this?

Stupid me:

$mode.method($method)

 
M

Mark Sparshatt

--- Roeland Moors said:
Stupid me:

$mode.method($method)
This won't do what you want. It'll return a Method
object rather can calling the method.

As has been mentioned in other emails you need to
write

$mode.send($method)

BTW is the code supposed to be using global rather
than local variables?






___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com
 
R

Roeland Moors

R> $mode.$method

$mode.send($method) # ruby will be able to call also private and
# protected methods

thanks I'm now using something like this:
$mode.send($method) if $mode.methods.include?($method)
 
R

Robert Klemme

Roeland Moors said:
Stupid me:

$mode.method($method)

No, that just returns the method object. You then still need to invoke
it.
=> "fooxxx"

But #send() is much simpler.

Btw, you know that you can do

testMethods = $mode.methods.select {|m| /^test/ =~ m}

or even

$mode.methods.select {|m| /^test/ =~ m}.each do |m|
$mode.send m
end

or

$mode.methods.each do |m|
$mode.send( m ) if /^test/ =~ m
end

But it's even more simple to use TestUnit for this...

Kind regards

robert
 

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
474,158
Messages
2,570,882
Members
47,414
Latest member
djangoframe

Latest Threads

Top