From: James Gray Date: 2009-07-12T01:51:13+09:00 Subject: Re: help for code understanding On Jul 11, 2009, at 11:07 AM, Li Chen wrote: > James Gray wrote: >> In plain English, it makes a new object of the same type as the >> current object and passes the current object as the argument to the >> constructor of the new object. > > > Thank you, James. Now I understand the code. But what is difference > between these two methods(follow your previous example codes): > > def make_another_object1 > self.class.new > end > > def make_another_object2 > self.clone > end > > Are they the same if self.class.new takes no argument? They are not the same. Have a look: >> class Copy >> def initialize(arg = nil) >> puts "Initializing a Copy..." >> @arg = arg >> end >> def make_a_copy >> self.class.new >> end >> end => nil >> c = Copy.new(:original) Initializing a Copy... => # >> c.clone => # >> c.make_a_copy Initializing a Copy... => # Notice how clone() didn't call initialize() and it did copy the instance variable. Calling the constructor could change things though, as I've shown here. clone() also duplicates some of Ruby's internal state, like whether or not an object is frozen?(). Calling new() would make a fresh new object though and thus lose such details. Hope that helps. James Edward Gray II