[LRUG] Ruby functions

Simon Sebright simonsebright at hotmail.com
Thu Oct 29 02:19:44 PDT 2009


Great thanks, Tom.  That's exactly what we were after.  Interesting, as with 
many things, it is implemented with a library class as opposed to being a 
language feature.  Contrast to delegates in C# for example.
Simon

--------------------------------------------------
From: "Tom Stuart" <tom at experthuman.com>
Sent: Thursday, October 29, 2009 9:54 AM
To: "London Ruby Users Group" <chat at lists.lrug.org>
Subject: Re: [LRUG] Ruby functions

> 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
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
> 



More information about the Chat mailing list