Why is the constructor method named initialize? Why not name it new to
be
consistent?
Mike S.
Why is the constructor method named initialize? Why not name it new to
be
consistent?
Mike S.
On Jun 12, 2007, at 10:34 AM, Mike S. wrote:
Why is the constructor method named initialize? Why not name it new
to be
consistent?
Typically, :new is a class method, which calls the instantiated
object’s :initialize instance method, if one is available, with the
parameters passed to :new.
You can override the class method :new (this is a good place to use
super), but be sure to return the newly minted object. Often you can
just override the :initialize instance method, however.
If there’s no :new class method in your class definition, then you’re
getting Object.new (or some other super class’s :new).
Mike S. wrote:
Why is the constructor method named initialize? Why not name it new
to be consistent?
I had this same question when I first started out. The answer I came
to realize is that “new” is a class method that allocates the object,
and “initialize” is the instance method that does the per-object setup
you want.
For more details on how I came to realize this, read the “new versus
initialize” section of this post:
Short URL: http://rubyurl.com/n1Q
Full URL:
http://groups.google.com/group/comp.lang.ruby/tree/browse_frm/thread/c3b22bf2d53bd68b/72313022abed07f9?rnum=1&q=matz+is+smart&_done=%2Fgroup%2Fcomp.lang.ruby%2Fbrowse_frm%2Fthread%2Fc3b22bf2d53bd68b%2F1b4160db0a57e90f%3Flnk%3Dgst%26q%3Dmatz%2Bis%2Bsmart%26rnum%3D1%26#doc_72313022abed07f9
Thanks! That link makes it much clearer.
Mike S.
Why is the constructor method named initialize? Why not name it new
to be
consistent?
Typically, :new is a class method, which calls the instantiated
object’s :initialize instance method, if one is available, with the
parameters passed to :new.
You can override the class method :new (this is a good place to use
super), but be sure to return the newly minted object. Often you can
just override the :initialize instance method, however.If there’s no :new class method in your class definition, then you’re
getting Object.new (or some other super class’s :new).
Would it be better to have initialize called ‘on_new’ so that the
connection is more firm?
Thoughts?
-=R
On 20 Nov 2008, at 23:46, Roger P. wrote:
If there’s no :new class method in your class definition, then you’re
getting Object.new (or some other super class’s :new).Would it be better to have initialize called ‘on_new’ so that the
connection is more firm?
Thoughts?
Unfortunately :on_new assumes that :initialize is only ever called
from :new, which isn’t always the case.
Ellie
raise ArgumentError unless @reality.responds_to? :reason
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs