Chapter 5. Arrays
Like all high-level languages, Ruby has built-in support for arrays, objects that contain ordered lists of other objects. You can use arrays (often in conjunction with hashes) to build and use complex data structures without having to define any custom classes.
An array in Ruby is an ordered list of elements. Each element is a reference to some object, the way a Ruby variable is a reference to some object. For convenience, throughout this book we usually talk about arrays as though the array elements were the actual objects, not references to the objects. Since Ruby (unlike languages such as C) gives no way of manipulating object references directly, the distinction rarely matters.
The simplest way to create a new array is to put a comma-separated list of object references between square brackets. The object references can be predefined variables (my_var), anonymous objects created on the spot (my string, 4.7, or MyClass.new), or expressions (a+b, object.method). A single array can contain references to objects of many different types:
a1=[]# => []a2=[1,2,3]# => [1, 2, 3]a3=[1,2,3,'a','b','c',nil]# => [1, 2, 3, "a", "b", "c", nil]n1=4n2=6sum_and_difference=[n1,n2,n1+n2,n1-n2]# => [4, 6, 10, -2]
If your array contains only strings, you may find it simpler to build your array by enclosing the strings in the w{} syntax, separated by whitespace. This saves you from having to write all those quotes and commas:
%w{1 2 3}# => ["1", "2", ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access