The first section of the chapter shows the most basic and common way to create an array, but there are alternatives (in Ruby, there are always alternatives). You can start by creating a new empty array by doing either
a = Array.new
a = 
Then you can add values to the array using <<:
a << 32 a << 'carrot'
If you’d prefer to use a method instead of an operator, either of these is equivalent to the preceding line:
a.push 'carrot' a.push('carrot')
(The sole difference is in how methods can be invoked. See the sidebar “Calling Ruby Methods” in Chapter 3.)
Whether you use << or push, the new item is added at the end of the array. Conversely, unshift adds elements to the beginning of the array:
a = [2, 3, 4] a.unshift(1) # [1, 2, 3, 4]
The insert method can be used to add an element anywhere. Its first argument is the index position for the new item; the second is the value itself:
a.insert(2, 2.5) # [1, 2, 2.5, 3, 4]
To add array elements:
Create an array:
writers = 
You can also use
writers = Array.new
Add some elements to the end of the array (Figure 4.8):
writers << 'Sedaris' writers << 'McEwan' << 'Diaz' writers.push('Bank') puts writers.inspect
Figure 4.8 Four elements are added to an array.
The first two lines demonstrate two different uses of the << operator. The second just shows that you can add multiple elements in one statement using this approach.
The third line invokes the push method for the same effect. Finally, the contents of the array are displayed.
Add an element to the beginning of the array (Figure 4.9):
writers.unshift('Hodgman') puts writers.inspect
Figure 4.9 The unshift method can be used to add an element to the beginning of an array.
The new array element will be added as the first value in the array, shifting every other element back one position.
Insert elements into the middle of the array (Figure 4.10):
writers.insert(3, 'Vowell') writers.insert(1, 'Stewart') puts writers.inspect
Figure 4.10 To add values anywhere in an array, call the insert method.
The first line adds a new name as the fourth element in the array (remember: arrays are indexed starting at 0). The second adds a new name as the second element. In both cases, subsequent elements are pushed back (you could use the index method to confirm the location of values).