new vs. initialize

J

Jeff Davis

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

Thanks,
Jeff Davis
 
M

Mark Hubbart

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
 
E

Eric Hodel

--Apple-Mail-23--8502834
Content-Transfer-Encoding: 7bit
Content-Type: text/plain; charset=US-ASCII; format=flowed

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

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>


--
Eric Hodel - (e-mail address removed) - http://segment7.net
FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04

--Apple-Mail-23--8502834
content-type: application/pgp-signature; x-mac-type=70674453;
name=PGP.sig
content-description: This is a digitally signed message part
content-disposition: inline; filename=PGP.sig
content-transfer-encoding: 7bit

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (Darwin)

iD8DBQFB/bvEMypVHHlsnwQRAvdfAJwM+zwcowgBfY41TIYiBF759kc1VgCffV91
ref1B33L3IVJgoXL14aJGG4=
=NJfI
-----END PGP SIGNATURE-----

--Apple-Mail-23--8502834--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top