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) |
|---|---|---|
|
|
Quotation marks |
|
|
|
Leading colon |
|
|
|
Square brackets |
|
|
|
Curly braces |
|
|
|
Two or three dots |
|
|
|
Forward slashes |
|
|
|
Dash, arrow, parentheses, braces |
|
Compare Ruby classes with their literal constructor characters and concrete examples. section 7.1
