Forum: Ruby Passing functions as arguments

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2ec38e324983babdd5c926c56f9e0c80?d=identicon&s=25 Alex Polite (Guest)
on 2006-01-15 22:41
(Received via mailing list)
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]
       ]


alex
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2006-01-15 23:09
(Received via mailing list)
formatmethod = Df.method(:datestr2time)
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2006-01-16 01:54
(Received via mailing list)
On Mon, 16 Jan 2006, Alex Polite wrote:

>
> 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
This topic is locked and can not be replied to.