Arrays

The class Array holds a collection of object references. Each object reference occupies a position in the array, identified by an integer index. You can create arrays by using literals or by explicitly creating an Array object. A literal array is a comma-delimited list of objects between square brackets:

 a = [3.14159, ​"pie"​, 99]
 a.​class​ ​# => Array
 a.​length​ ​# => 3
 a[0] ​# => 3.14159
 a[1] ​# => "pie"
 a[2] ​# => 99
 a[3] ​# => nil

You can create an empty array with either [] or by directly calling Array.new:

 b = Array.​new
 b.​class​ ​# => Array
 b.​length​ ​# => 0
 b[0] = ​"second"
 b[1] = ​"array"
 b ​# => ["second", "array"]

As the example shows, array indices start at zero. Index an array with a non-negative ...

Get Programming Ruby 3.3 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.