liveBook · Manning

Literal constructor

As explained in The Well-Grounded Rubyist, Fourth Edition

A literal constructor is syntax that creates a value or object directly without an explicit call to a class constructor method such as new.

A literal constructor creates certain Ruby objects through dedicated syntax instead of an explicit call to new. Using one brings a new object into existence, and these forms are common even when another instantiation route exists. section 7.1

Ruby’s built-in literal constructors include:

  • Strings: "new string" or 'new string'. section 7.1
  • Symbols: :symbol or :"symbol with spaces"; Symbol has no new constructor. section 7.1
  • Arrays: [1, 2, 3, 4, 5]; hashes: {"New York": "NY", "Oregon": "OR"}. section 7.1
  • Ranges: 0..9 or 0...10; regular expressions: /([a-z]+)/. section 7.1
  • Procs and lambdas: ->(x, y) { x * y }. section 7.1

Notation versus new

String.new and Array.new explicitly invoke new, while "new string" and [1, 2, 3] create objects through literal syntax. The notation is not interchangeable with every use of similar punctuation: [] can be a literal array constructor or a call to an object's [] method, and curly braces can delimit a code block rather than a hash literal. Context determines the meaning. section 7.1

Table 7.1 Built-in Ruby classes with literal constructors

Class

Literal constructor

Example(s)

String

Quotation marks

"new string"

'new string'

Symbol

Leading colon

:symbol

:"symbol with spaces"

Array

Square brackets

[1,2,3,4,5]

Hash

Curly braces

{"New York": "NY", "Oregon": "OR"}

Range

Two or three dots

0..9 or 0...10

Regexp

Forward slashes

/([a-z]+)/

Proc (lambda)

Dash, arrow, parentheses, braces

->(x,y) { x * y }

Compare Ruby classes with their literal constructor characters and concrete examples. section 7.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines the feature, catalogs its forms, and explains notation ambiguity without detailing object-creation internals.
Examples
Uses strings, symbols, arrays, hashes, ranges, regular expressions, lambdas, String.new, Array.new, and ambiguous [] or {} notation.
What it assumes
Assumes familiarity with Ruby classes, objects, methods, and basic syntax while reinforcing built-in object creation.
What you can do after
Evaluate Ruby punctuation correctly and recognize when it creates a literal object or invokes a method in context.
How it connects
Connects literal constructors with classes, objects, new, conversion methods, syntactic sugar, operator overloading, and code blocks.

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.