Passing functions as arguments

A

Alex Polite

I'm just starting out with ruby.

I'm trying to make an array of arrays containing [a pattern, a string,
a function]

Patterns and strings went fine but when I put in a function ruby tries
to eval it and complains about not getting right number of arguments.

Is there any way to escape a method so that you can put it in a list
or pass it as an argument to another function?

pats =3D [
[/:BEGIN:(.*)/, "DTSTART", Df.datestr2time ],
[/:DUE:(.*)/, "DUE", Df.datestr2time]
]


alex
 
P

Phil Tomson

I'm just starting out with ruby.

I'm trying to make an array of arrays containing [a pattern, a string,
a function]

Patterns and strings went fine but when I put in a function ruby tries
to eval it and complains about not getting right number of arguments.

Is there any way to escape a method so that you can put it in a list
or pass it as an argument to another function?

pats =3D [
[/:BEGIN:(.*)/, "DTSTART", Df.datestr2time ],
[/:DUE:(.*)/, "DUE", Df.datestr2time]
]

How about:

pats = [
[/:BEGIN:(.*)/, "DRSTART", Df.method:)datestr2time)],
[/:DUE:(.*)/, "DUE", Df.method:)datestr2time)]
]



Phil
 
A

ara.t.howard

I'm just starting out with ruby.

I'm trying to make an array of arrays containing [a pattern, a string,
a function]

Patterns and strings went fine but when I put in a function ruby tries
to eval it and complains about not getting right number of arguments.

Is there any way to escape a method so that you can put it in a list
or pass it as an argument to another function?

pats = [
[/:BEGIN:(.*)/, "DTSTART", Df.datestr2time ],
[/:DUE:(.*)/, "DUE", Df.datestr2time]
]

yes. but you don't need to, simply store the name of the method and use
'send':

harp:~ > cat a.rb
table =
[%r/:BEGIN:(.*)/, "DTSTART", "datestr2time"],
[%r/:DUE:(.*)/, "DUE", "datestr2time"]

#
# mock-up
#
class Df
def self::datestr2time string
p string
end
end

txt = <<-txt
:BEGIN:
:DUE:
txt

txt.each do |line|
table.each do |dispatch|
pat, string, method = dispatch
if pat.match line
Df::send method, string
end
end
end


harp:~ > ruby a.rb
"DTSTART"
"DUE"


regards.

-a
 
T

Timothy Goddard

'send' is _much_ slower than 'method.call'. The first example is
probably the clearest and most efficient way to do this, especially in
a high-use function.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top