Ruby Constructors: new or initialize?

I gave a brief explanation of new and initialize in Chapter 1. At that stage, you had not examined the differences between Ruby’s class and instance methods and variables, so it was not possible to give a full discussion of how new and initialize work together. Because these are such important methods, you’ll look at them in more detail now.

The method responsible for bringing an object into being is called the constructor. In Ruby, the constructor method is called new. The new method is a class method that, once it has created an object, will run an instance method named initialize if such a method exists.

In brief then, the new method is the constructor, and the initialize method is used to initialize the ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.