Arrays

An array is a container class that holds a collection of objects indexed by an integer. Any kind of object may be stored in an array, and any given array can store a heterogeneous mix of object types. Arrays grow as you add elements. Arrays can be created using array.new or via literals. An array expression is a series of values between brackets [ ]:

[]

An empty array (with no elements)

[1, 2, 3]

An array of three elements

[1, [2, 3]]

A nested array

General delimited string array

You can construct arrays of strings using the shortcut notation, %W. Only whitespace characters and closing parentheses can be escaped in the following notation:

%w(foo bar baz)        # ["foo", "bar", "baz"]

Get Ruby in a Nutshell 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.