Method to Proc

G

GGarramuno

Is there a way to turn a method into a proc stored in a variable?
Something similar to Perl's \& notation.

Say I have a method written and I want to call it indirectly, thru a
proc object. I basically want to get the "address" of the method (or
have a proc object referring to it)

def myfunc(t)
puts t
end

t = \&myfunc #this line is perl's way of doing it
t.call("hello")

The idea behind calling functions like these indirectly is so as to
have the ability of the proc object to refer to built methods and/or
on the fly written procs.
Ruby seems to have this functionality, but I cannot find the proper
syntax.
 
G

gabriele renzi

il 4 Jan 2004 11:17:25 -0800, (e-mail address removed) (GGarramuno) ha
scritto::
Is there a way to turn a method into a proc stored in a variable?
Something similar to Perl's \& notation.

Say I have a method written and I want to call it indirectly, thru a
proc object. I basically want to get the "address" of the method (or
have a proc object referring to it)

hope this helps:
irb(main):001:0> def f; puts 'ciao' ; end
=> nil
irb(main):002:0> my=method:)f)
=> #<Method: Object#f>
irb(main):003:0> my.call
ciao
=> nil
irb(main):004:0> myproc=my.to_proc
=> #<Proc:0x0280ec78@(irb):4>
irb(main):005:0> myproc.call
ciao
=> nil


and remember you can expand a proc object (or a Method object) into a
block with
&procobject
 

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
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top