[Ironruby-core] Delegates (agian)

Charles Oliver Nutter charles.nutter at sun.com
Thu Oct 25 17:13:37 EDT 2007

Dermot Hogan wrote:
> I've been thinking about delegates and IronRuby.
> After playing around with trying to work with a delegate in Ruby (procs,
> lambdas and god-knows-what) I've come to the conclusion that delegates
> have to be supported in a more fundamental way than trying to make a
> block work as a delegate.
> First off, I think IR has to support adding and removing delegates via
> '+=' and '-='. That's how every other .NET language does it (IronPython
> included). It doesn't seem right to use '<<' because there isn't an
> equivalent '>>' (though I suppose you could define one). Anyway, you
> have to be able to remove a delegate as well as add one.

A problem you've missed here is that x += y and x -= y are (always) 
equivalent in Ruby to x = x + y and x = x - y. Unless + or - mutate the 
original object, now mutation will occur.

Even in the case where they may be attributes:

class Foo
   attr_accessor :a

f = Foo.new
f.a = 1
f.a += 2
# equivalent to
f.a = f.a + 2

The only way this might be able to work is if you defined + against a 
delegate to return the full collection of delegates, and then assignment 
updates the original list...

class DelegateList
   def initialize(*delegates)
     @delegates = delegates

   def +(other)
     DelegateList.new(other, *@delegates)

f = Foo.new
f.a = DelegateList.new(some_delegate)
f.a += some_other_delegate

Thoughts? We've had similar questions about how to handle event listener 
registration in JRuby, though there's no legacy operator syntax to 
support in our case.

- Charlie

More information about the Ironruby-core mailing list