New vs. initialize

If MyClass.new calls the initialize method, what calls the new method? What if both are defined?

Thanks,
  Jeff Davis

Hi,

If MyClass.new calls the initialize method, what calls the new method?
What if both are defined?

*You* call the new method. It's pre-defined in Class to work something
like this:

class Class
  def new
    obj = self.allocate # allocates the object
    obj.initialize # calls the object's initialize method
    return obj # returns the object
  end
end

You can redefine new to do anything you want, remembering that people
will expect it to return an object of that class.

cheers,
Mark

···

On Mon, 31 Jan 2005 13:49:43 +0900, Jeff Davis <jdavis-list@empires.org> wrote:

You call the new method on a Class when you want a new instance of that class.
The class calls #initialize to set up the instance for you.

Here's how the two tie together in Ruby, expressed as Ruby code.

class MyClass
   def self.new(*args, &block) # class method
  puts "called MyClass.new"
     obj = allocate
     # #initialize is a private method, so we use send to invoke it.
     obj.send :initialize, *args, &block
     return obj
   end

   def initialize # instance method
     puts "called MyClass#initialize"
   end
end

p MyClass.new

# => called MyClass.new
# => called MyClass#initialize
# => #<MyClass:0x13356c>

PGP.sig (186 Bytes)

···

On 30 Jan 2005, at 20:49, Jeff Davis wrote:

If MyClass.new calls the initialize method, what calls the new method? What if both are defined?

--
Eric Hodel - drbrain@segment7.net - http://segment7.net
FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04