New/initialize


#1

Just a point of clarification.

When I call
Obj.new()

I actually call the
clall Obj
def initialize()
end
end

so there is an implied connection between new() and initialize()?

Historically is there some reason why we didn’t just stick with the
‘def new()’
or did I miss something.


#2

On Apr 10, 2006, at 11:07 AM, Tom A. wrote:

When I call
Obj.new()

I actually call the
clall Obj
def initialize()
end
end

Not exactly. You call Object::new. Object::new calls initialize
after allocating a new instance.

so there is an implied connection between new() and initialize()?

There is an explicit connection between Object::new and
Object#initialize

Object::new is implemented something like this, but in C:

class Object
def self.new(*args, &block)
obj = allocate
obj.send(:initialize, *args, &block)
return obj
end
end

Historically is there some reason why we didn’t just stick with the
‘def new()’
or did I miss something.

That would be an instance method. Object::new is a class method.


Eric H. - removed_email_address@domain.invalid - http://blog.segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com


#3

On 4/10/06, Tom A. removed_email_address@domain.invalid wrote:

so there is an implied connection between new() and initialize()?

Historically is there some reason why we didn’t just stick with the
‘def new()’
or did I miss something.

No, you actually call Obj::new. This is a method on Obj; this method
looks something like this, although it’s written in C:

class Obj
class << self
def new(*args, &block)
obj = self.allocate
obj.send(:initialize, *args, &block)
obj
end
end
end

-austin


#4

On 4/10/06, Tom A. removed_email_address@domain.invalid wrote:

end

so there is an implied connection between new() and initialize()?

Historically is there some reason why we didn’t just stick with the
‘def new()’
or did I miss something.

“new” allocates space for the new object and creates it. It then calls
“initialize” to initialize the newly created object. Typically that’s
that only part you want to customize which is why you write an
“initialize” method instead of a “new” method.


#5

new() is actually just a class method of the class object (Obj). You
can create your own method if need be:

class Obj
def self.new
super

end
end

Calling ‘super’ is pretty important otherwise your object is not
properly instantiated (I think). You can also wind up with the wrong
kind of object if you’re not careful

irb(main):001:0> class Obj
irb(main):002:1> def self.new
irb(main):003:2> return “Hello!”
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> o = Obj.new
=> “Hello!”
irb(main):008:0> o.class
=> String

Farrel


#6

That would be an instance method. Object::new is a class method.

Ding!
Light went on. Thanks.