liveBook · Manning

Array literal

As explained in The Well-Grounded Rubyist, Fourth Edition

An array literal is Ruby syntax that constructs an array using square brackets and optional element expressions.

An array literal constructs an array with square brackets. Write elements between the brackets, separating them with commas; elements may have different types, including another array. section 9.2.1

A mixed array

a = [1, 2, "three", 4, []] creates an array containing integers, a string, and a nested empty array. Ruby also lets you retrieve an element with bracket indexing, as in array[0]. section 9.2.1

a = [1,2,"three",4, []]

Inspect a literal containing several value types and a nested array. section 9.2.1

Square-bracket literals provide a compact alternative to other array-creation forms:

  • Use [] for an empty array. section 9.2.1
  • Use comma-separated values such as [1, 2, "three"] for an immediately populated array. section 9.2.1
  • Distinguish literals from Array.new and specialized %w and %i notations, which create arrays through different syntax or methods. section 9.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines square-bracket construction and illustrates mixed and nested elements, while deferring broader array initialization mechanics.
Examples
Uses empty, mixed, nested, and indexed arrays as compact interactive Ruby examples.
What you can do after
Builds array values from scratch using square brackets and retrieves elements with bracket indexing.
How it connects
Connects array literals with array indexing, Array.new, and specialized %w and %i notations.

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.