Ruby Array Basics: Creating, Modifying, and Iterating

rubyarrayIf you look at the official Ruby documentation definition of arrays, you’ll see that an array is defined as an ordered, integer-indexed collection of objects. While that may be accurate, it’s a very dry way of explaining what array is and how to use it. When you start working with Ruby, or take a Beginners Ruby Programming course, you’ll find yourself using arrays constantly to keep track of lists of strings, to store references to items you are working with, and to iterate through groups of objects in sequence.

Definition of an Array

So let’s break down that definition. What do all of those terms mean, and how are they going to affect the way you work with arrays when you start programming in Ruby?

Ordered

The first thing to learn about arrays is that they are ordered. An array starts at a specific point, goes forwards to the end, and then stops. Each one of the items in an array has specific address, and you can always count on each address being one higher than the previous address. This is one feature that makes arrays so useful. You can store anything in an array, and know that unless the array has been modified, whatever came before it will always come before it, and whatever comes after it will always come after it. Unlike some data structures, the ordering in an array is significant. You can depend on it.

Integer-Indexed

When they say that an array is integer indexed, what they mean is that each item in the array can be accessed by referencing an integer that represents its position in the array. The item referenced by passing any specific integer will always come back when you reference that specific integer, as long as the array has not been modified. This allows you to use an array as a queue, or as a list of items that will always be in the same order, and can always be referenced by their order.

Collections

An array is a collection, meaning that a single array is actually a reference in memory to a variety of other objects. An array can be empty, or it can have a huge number of objects in it, including other arrays, but it will still be the same single collection.

Of Any Object

One thing that makes Ruby different from some other languages is that an array can contain any type of legitimate Ruby object. Even if you create a new object type, an existing array can be used to hold one or more of that object. Arrays can also hold objects of different types, making them very flexible.

Zero-Indexed

Like many programming languages, Ruby uses a zero index for its arrays. What this means is that the first object in an array is indexed as iten number zero. The second object is item number one. And the address of the final object can be calculated by getting the length of the array, subtracting one, and using that as the index for that object.

Creating Arrays

Ruby makes it very easy to create an array. The syntax for an array is a set of square brackets. At its most basic, and empty array can be created just by assigning an empty set of square brackets to a variable.

a = []

This creates a legitimate array, although it’s not very useful if it doesn’t have anything in it. Often you will create an empty array at the beginning of a method to contain objects that you will be creating and putting into the year it’ll later time.

You can also create an array using the “new” method of the Array class, and passing the number of items that you want the array initialized with.

a = Array.new
a = Array.new(20)

Initializing an empty array with a number of items creates the space in memory for as many items as you want the array to hold when it is created, but arrays can grow and shrink as needed. And you can find out if it rains empty just by using the empty method, but a question mark.

a.empty?
=> true

Arrays can also be initialized with contents of the time that they’re declared. To do this, you would create a variable and decided to value of several objects between square brackets, separated by commas.

b = [x, y, z]

It doesn’t matter one bit what x, y, and z represent in the above expression. They could be variables that reference strings, integers, or any type of legitimate Ruby object. All you have to do to create an array is define a variable, and assign it the values that you want inside of square brackets, separated by commas.

x = "cat"
y = 5
z = true
b = [x, y, z]
b
=> ["cat", 5, true]

Accessing Values

The reason it’s important that the items in arrays are kept in order is that this makes it very easy to access the items in an array. You access an item bypassing the address of the item that you want to the variable name the theoretic, and it will return the value that lives at that address. The syntax for doing this is to type the name of the variable, followed by a square bracket with the number of the address inside of it.

So for example, using the array that we just created above, the first item lives at address zero, and the second item lives at address one. We would access these 2 Items this way:

b[0]
=> "cat"
b[1]
=> 5

Another way of accessing the items and arrays to use the at method, again passing in the index of the item that you want returned.

b.at(2)
=> true

The choice of which method to use depends entirely on the type of programming that you’re doing. There may be times when it’s more convenient to pass in a numerical index, and other times when it’s better to call the at method.

Also, just as you can get the object referenced by specific index number, you can also get the index number of the first position of a particular object by passing in a reference to the object and using the index method.

b.index(true)
=> 2

If the value that you pass in matches more than one object in the rate, you’ll get the address of the first object, not of all of the objects. And if you try to access an item that exists beyond the size of the array, Ruby will return nil.

b[20]
=> nil

Adding Items to Arrays

One of the things that make arrays flexible in Ruby is the fact that you can easily add and remove items. To add an item into an array at the end, you push it on.

b.push("dog")
=> ["cat", 5, true, "dog"]

If you want to add value to the beginning of an array, you use the unshift method.

b.unshift("6.23")
 => ["6.23", "cat", 5, true, "dog"]

It should be noted that these methods are destructive, which means that they do alter the actual value of the original array. As a convenience, the push and unshift methods also return the new value of the complete array.

Other methods are also available for adding items to the middle of an array, such as insert. You can learn more about ways to use some of these in a good Ruby Programming for Beginners class.

Removing Items

Similar methods exist for removing items from an array. The corollary to the push command is the pop commands, which removes the last item in an array, and returns the value of that item.

b.pop
 => "dog"

To remove the first item, you use the shift method.

b.shift
 => "6.23"

Again, in both of these cases, the commands are destructive. Even though the modified array is not returned, be final array that you’re left with after a push or a shift will no longer include the value that was just returned.

b
 => ["cat", 5, true]

And of course, methods also exist for deleting items of specific index addresses within an array. If you want to find out more about methods like delete_at, courses such as Ruby Training 360 should have you covered.

Reversing and Sorting

Just to demonstrate the significance of the consistent ordering of an array, it’s possible to use commands such as sort, or reverse, to change the indexing of the items without actually changing the contents of an array. Arrays are smart enough to keep track of all of the items, even if the addresses are being modified.

b.reverse
 => [true, 5, "cat"]

If you have an array of items that are of similar types, it’s also possible to sort an array. For example, if you have an array of strings, the sort method will rearrange that array based on the alphabetical ordering of the strings in the array.

strs = ["book", "table", "computer", "mouse"]
 => ["book", "table", "computer", "mouse"] 
strs.sort
 => ["book", "computer", "mouse", "table"]

Note that in this case, the sort method is nondestructive. It will return the result of sorting the array, but if the original array unsorted.

strs
 => ["book", "table", "computer", "mouse"]

If you want the array permanently sorted, use the sort command with a bang or exclamation mark after it.

strs.sort!
 => ["book", "computer", "mouse", "table"]
strs
 => ["book", "computer", "mouse", "table"]

And of course, Ruby offers a wide range of built-in commands that make it easy to modify the content inside of an array very specifically. You can change an item at a specific index, or even change a range of items between two indices. If you want to find out more about working with arrays at this level of detail, you might want to try a course such as Advanced Ruby Programming, 10 Steps to Mastery.

Getting Information

Without modifying the content if you’re Ray, there’re a number of ways that you can examine the array and find out more about its contents. these can be very useful if you need you figure out whether the over has the specific items that you need, or what items live at specific places in the rate. One of the most common methods that you will use is length, which tells you how many items they have a has in it.

b.length
=> 3

Just referencing the variable name of your array on the command line will return the contents of the array, but you can also use the inspect method if you need your results string-escaped so that they can easily be used in other places.

b.inspect
 => "[\"cat\", 5, true]"

Ruby also has a number of very convenient methods such as first and last, which help you identify the first and last items in your array.

b.first
 => "cat" 
b.last
 => true

If you’re going to use Ruby with a framework such as Rails, you’ll find yourself using methods like these a lot, as well as a number of other very convenient methods that are defined within the rails framework. To learn more about Ruby and Rails, another great course to consider is Learn Ruby on Rails from Scratch.

Iterating

Of course the real value of arrays comes when you start to iterate over one. Iterating over an array means going to each item within the array and performing some function or calculation that makes use of the information at that position. When you iterate over an array, you go in order, all the way from a starting point to an ending point that you can define, although usually you start at the beginning and stop at the end.

b.each { |item| print item, ": \n" }
cat: 
5: 
true:

You can also use other methods such as map to go over each item in an array, perform a calculation with it, and output the results as a new array with each item modified by that calculation. Methods like this are most convenient for arrays that contains similar items, such as our strs array of strings.

strs.map{ |item| item + "?" }
 => ["book?", "table?", "computer?", "mouse?"]

The map function does not modify the original array, but returns the new array which you need to save into a new variable if you want to preserve it. Again, if you want to make a map destructive, you can add a bang or exclamation mark to it.

strs
 => ["book", "table", "computer", "mouse"] 
strs.map!{ |item| item + "?" }
 => ["book?", "table?", "computer?", "mouse?"] 
strs
 => ["book?", "table?", "computer?", "mouse?"]

That should be enough to get you started experimenting with arrays in Ruby. If you want to dive in quickly, check out some of the great courses on Udemy.