### Need a reference text for the Ruby programming language? Get the Well-Grounded Rubyist.
You can use arrays to group similar data into a single entity, instead of having to create multiple variables just to separate that same kind of data. Ruby makes it really convenient for you to work with arrays: you can use bracket notation to access and set elements and use stack/queue-like methods to manipulate its data (i.e. push, pop, unshift, shift). Furthermore, you can easily go through an array and use that data in some form using iterators like each, map, select, and reject.
Creating an Array
You can either create an empty array or start it off with a few elements. To start off from scratch, you can use the [] empty array:
animals = []
Then, you would populate the array with elements using the operations we will learn later.
Otherwise, you can just initialize it with some elements:
animals = ["dog", "cat", "bear", "horse", "eagle"]
Arrays are denoted within brackets and have to be comma-separated. The array above is an array of strings and has 5 elements. Although we used strings above, you could use just about any data type because Ruby allows for arrays to have a mix of different types. For example, the following would be okay too:
array = [12, "dog", 3, "cat", 4.65, 0, "eagle"]
The above is an array of mixed data types -- it has integers, floats, and strings.
Accessing Elements
Coming back to our animals example, we can access each element using bracket notation:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals[0] is the first element of the array ("dog")
animals[4] is the last element of the array ("eagle")
To access elements in an array, you start counting from zero: so the first element will be at position 0 and the last element will be at position given by the size of the array MINUS one. In the case above, we have a 5-element array, so the position of the last element is 5 - 1, which is 4.
You can determine the size of the array in Ruby using the length or size method:
animals.size
animals.length
They both return the same thing and will give you the number of elements in the array.
Modifying Array At the End
You can add new elements to the end of the array using the push method:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals.push("pigeon")
=> ["dog", "cat", "bear", "horse", "eagle", "pigeon"]
Note how the new element "pigeon" was added to the end of the array. This is like a stack for those of you familiar with basic data structures.
To remove an element from the end of the array, you can use pop:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals.pop
=> "eagle"
=> ["dog", "cat", "bear", "horse"]
Ruby gives you the popped element as the return value from the pop method, you can do something with that. The element is removed from the end of the array, though.
Modifying the Array At the Beginning
There are two other methods that allow you to add/remove elements from the beginning of the array instead of at the end: they are unshift and shift.
You can use unshift to add an element to the beginning of an array:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals.unshift("dinosaur")
=> ["dinosaur", "dog", "cat", "bear", "horse", "eagle"]
The new element has been added to the front of the array. This is like a queue for those of you familiar with basic data structures.
If you want to remove an element from the beginning of the array, use shift:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals.shift
=> "dog"
animals
=> ["cat", "bear", "horse", "eagle"]
When you do a shift operation, the element at the beginning of the array is removed and then returned to you so you can do something with it.
Modifying Specific Elements
You can use bracket notation to modify specific elements of an array at a certain index. For example, given the array of animals, you could replace the second element, "cat", with something else:
animals = ["dog", "cat", "bear", "horse", "eagle"]
animals[1] = "turtle"
animals
=> ["dog", "turtle", "bear", "horse", "eagle"]
Notice how the second element (whose index is 1) was replaced by "turtle."
Iterating Over Array
You can go through each element in the array using the each iterator. It is part of the Enumerable module. You can find many useful things there, so check it out. Anyway, here is an example:
animals = ["dog", "turtle", "bear", "horse", "eagle"]
animals.each { |animal| puts animal }
The above will go through each element in the array of animals and display its value (each on its own line). The each iterator accepts a block (denoted within braces) whose block parameter variable will take in each array element, one at a time, starting from the first one up to the last one, and then do something with it. In this case, I am using the puts statement to display each element's value.
Output:
dog
turtle
bear
horse
eagle
Other useful iterators are map, select, and reject. I invite you to look them up in the Ruby documentation. Now, let us see how to iterate over an array using a plain while loop:
animals = ["dog", "turtle", "bear", "horse", "eagle"]
index = 0
while index < animals.length
puts animals[index]
index += 1
end
The above uses the index variable to keep track of the location in the array. It starts off at 0 because the first element of the array is at position 0. Then, the loop condition is that the index is less than the number of elements in the array. Remember the last element is always the array size MINUS one. Inside the loop, you just display the value of the element at position index in the animals array. At the end of the loop, just before the end keyword, make sure to have the increment for index, so we do not end up with an infinite loop. The output of the above construct will be:
dog
turtle
bear
horse
eagle
Conclusion
Ruby makes it really nice and intuitive to work with arrays. You can think of them as stacks or queues, too. You can easily create, access, and modify its elements using Ruby's built-in methods. Furthermore, the Enumerable module has some interesting methods and iterators that allow you to extract certain pieces of information from Arrays. Don't forget to check that out as well! :) Thank you for reading and have fun!
Looking for a reference text for Ruby? Get the Well-Grounded Rubyist.