liveBook · Manning

Constructor method

As explained in The Well-Grounded Rubyist, Fourth Edition

A Ruby constructor is the class method conventionally named new that creates and returns an instance of the class.

To make an object from a class, send the class the message `new`: `obj = Object.new`. `new` is a constructor method: it creates and returns a new instance of that class. A class can receive messages because Ruby classes are themselves objects. section 3.1

ticket = Ticket.new
puts ticket.event

`Ticket.new` creates a ticket instance; `ticket.event` then calls a method on that instance. The two calls have different receivers. section 3.1

Constructors can also accept arguments or a block that affects the resulting object. `Array.new` makes an empty array with no arguments. Give it a size and the positions start as `nil`; give it a second argument and every position starts with that value. section 9.2.1

Shared value or fresh value?

`Array.new(3, "abc")` puts the same string object in all three positions. Mutating that string through one position changes what you see through the others. Use `Array.new(3) { "abc" }` when each position needs a separate string: the block runs once per position. section 9.2.1

>> Array.new(3) { |i| 10 * (i + 1) }       1
=> [10, 20, 30]                         2

The block receives each position’s index, so `Array.new(3) { |i| 10 * (i + 1) }` produces `[10, 20, 30]`. section 9.2.1

`new` is not the only way to obtain every kind of object: `[]` is a literal way to create an array. Conversely, some constructors produce objects that need cleanup. `File.new("code/ticket2.rb")` returns a file handle opened for reading if the file exists; otherwise it raises an exception. Close a handle opened this way when finished. section 9.2.1 section 12.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines `new` as a class-directed constructor and works through array arguments and blocks, without detailing constructor implementation.
Examples
Uses `Object.new`, `Ticket.new`, several `Array.new` forms, and `File.new`.
What it assumes
Assumes familiarity with method calls and class definitions while defining what `new` does.
What you can do after
Apply `new` to create instances, choose safe array initialization, and close file handles opened with `File.new`.
How it connects
Connects constructors to classes, instances, method calls, array literals, blocks, and file handles.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.