[MacRuby-devel] #init & #initialize

Eloy Duran eloy.de.enige at gmail.com
Sat May 17 06:55:21 PDT 2008


In the RubyCocoa layer I would like to have #initialize called from  
#init,
because in RC it was allowed to use #initialize and thus many classes  
do this.

Anyways, here's some test code, please note the comments and the  
output which are basically my questions :)

Cheers,
Eloy

#!/usr/local/bin/macruby

class Foo
   def init
     if super
       puts 'Foo init'
       self
     end
   end

   def initialize
     puts 'Object'
   end
end

class Bar < NSObject
   def init
     if super
       puts 'Bar init'
       self
     end
   end

   def initialize
     puts 'NSObject'
   end
end

# Calls only initialize which is a good thing because it's a "Object"  
subclass.
Foo.new
# => Object

# Calling new on a NSObject subclass calls initialize, but NOT init!!!??
Bar.new
# => NSObject

# Calls only init and NO initialize
Bar.alloc.init
# => Bar init

# Add behaviour to have initialize called from init
class NSObject
   # Note: Should I somehow alias the original NSObject#init?
   # Trying to alias it results in a NoMethodError.
   def init
     initialize
     self
   end
end

# Calls init and then initialize.
Bar.alloc.init
# => NObject
# => Bar init


More information about the MacRuby-devel mailing list