concept array in category ruby

appears as: rrays, array, n array, rray, An array, Arrays, The array
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

Ruby sees all data structures and values—from simple scalar (atomic) values like integers and strings, to complex data structures like arrays—as objects. Every object is capable of understanding a certain set of messages. Each message that an object understands corresponds directly to a method—a named, executable routine whose execution the object has the ability to trigger.

An array is an ordered collection of objects—ordered in the sense that you can select objects from the collection based on a consistent, consecutive numerical index. You’ll have noticed that we’ve already used arrays in some of the examples earlier in the book. It’s hard not to use arrays in Ruby. An array’s job is to store other objects. Any object can be stored in an array, including other arrays, hashes, file handles, classes, true and false ... any object at all. The contents of an array always remain in the same order unless you explicitly move objects around (or add or remove them).

An array is a numerically ordered collection. Any object you add to the array goes at the beginning, at the end, or somewhere in the middle. The most general technique for inserting one or more items into an array is the setter method []= (square brackets and equal sign). This looks odd as a method name in the middle of a paragraph like this, but thanks to its syntactic sugar equivalent, []= works smoothly in practice.

To use []=, you need to know that each item (or element) in an array occupies a numbered position. Arrays in Ruby are said to be “zero-based” or “zero-origin indexed.” Thus, the first element is at position zero (not position one). The second element is at position one, and so forth.

To add an object to the beginning of an array, you can use unshift. After this operation,

a = [1,2,3,4]
a.unshift(0)

the array a now looks like this: [0,1,2,3,4].

To add an object to the end of an array, you use push. Doing this,

a = [1,2,3,4]
a.push(5)

results in the array a having a fifth element: [1,2,3,4,5].

You can also use a method called << (two less-than signs), which places an object on the end of the array. Like many methods whose names resemble operators, << offers the syntactic sugar of usage as an infix operator. The following code adds 5 as the fifth element of a, just like the push operation in the last example: