[LRUG] Ruby functions

Tom Stuart tom at experthuman.com
Thu Oct 29 01:54:25 PDT 2009


On 29 Oct 2009, at 07:15, Simon Sebright wrote:
> Secondly someone asked if functions were first-class objects and if  
> you can for example get the code for a function.  I rather think the  
> ruby way is to use blocks as a way to get functions called back.  Or  
> maybe to turn them into a proc object?

Ruby doesn't really call anything a "function"; mostly you've got  
blocks (syntactic chunks of Ruby code), procs (closure-style objects  
that can be called), and methods (named blocks of code that can be  
invoked in the context of an instance using dot notation).

Procs are the first-class objects which most closely correspond to  
"functions" in Ruby. However, to answer your question, you can ask any  
object for a Method object corresponding to one of its methods, which  
mostly works like a souped-up proc, i.e. it's a closure that's also  
bound to the instance that you got it from:

 >> class Foo
 >>   def initialize(n); @n = n; end
 >>   def foo; "foo: #{@n}"; end
 >> end
=> nil
 >> f = Foo.new(42)
=> #<Foo:0x101109698 @n=42>
 >> f.foo
=> "foo: 42"
 >> m = f.method(:foo)
=> #<Method: Foo#foo>
 >> m.call
=> "foo: 42"

Note that you can also unbind a Method object from its instance to get  
an UnboundMethod object, which can then be rebound to another instance  
of the same class:

 >> g = Foo.new(43)
=> #<Foo:0x100630000 @n=43>
 >> n = m.unbind
=> #<UnboundMethod: Foo#foo>
 >> n.bind(g).call
=> "foo: 43"

Or alternatively you can get an UnboundMethod directly from a class  
and then bind it to an instance:

 >> o = Foo.instance_method(:foo)
=> #<UnboundMethod: Foo#foo>
 >> o.bind(f).call
=> "foo: 42"

Cheers,
-Tom



More information about the Chat mailing list