Understanding Ruby Arrays

Revision as of 20:21, 26 November 2007 by Neil (Talk | contribs)

Revision as of 20:21, 26 November 2007 by Neil (Talk | contribs)

In Understanding Ruby Variables we looked at storing data (such as numbers, strings and boolean true or false values) in memory locations known as variables. The variable types covered in those chapters were useful for storing one value per variable. Often, however, it is necessary to group together multiple variables into a self contained object. This is where the concept of Ruby Arrays comes in. The objective of this chapter, therefore, is to introduce the concept of Arrays in Ruby and provide an overview of the creation and manipulation of such objects. In the next chapter (Advanced Ruby Arrays) we will look at more ways to work with arrays.

What is a JavaScript Array

A Ruby array is an object that contains a number of items. Those items can be variables (such as String, Integer, Fixnum Hash etc) or even other objects (including other arrays to make a multidimensional array). Once you have grouped all the items into the array you can then perform tasks like sorting the array items into alphabetical or numerical order, accessing and changing the value assigned to each array item, and passing the group of items as an argument to a Ruby function.

In this chapter we will look in detail at how to create and manipulate JavaScript arrays.

How to Create a Ruby Array

Ruby provides a number of mechanisms for creating an array. Arrays essentially involve the use of the Ruby Array class. We could, therefore, create an uninitialized array using the new method of the Array class:

days_of_week = Array.new

We now have an array called days_of_week with nothing in it. In fact, we can verify if an array is empty by calling the empty? method of the Ruby Array class which will return true if the array is empty:

days_of_week.empty?

We can also initialize an array with a preset number of elements by passing through the array size as an argument to the new method:

days_of_week = Array.new(7)
=> [nil, nil, nil, nil, nil, nil, nil]

Note that when we preset the size, all the elements are initialized to nil. Now we need some way of populating an array with elements.


Populating an Array with Data

Having created an array we need to add some data to it. One way to do this is to place the same data in each element during the created process:

days_of_week = Array.new(7, "today")
=> ["today", "today", "today", "today", "today", "today", "today"]

Another option is to use the [] method of the Array class to specify the elements one by one:

days_of_week = Array[ "Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun" ]
=> ["Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun"]

This can also be abbreviated to just the array name and the square brackets:

days_of_week = [ "Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun" ]

This will not only create the array for us, but also populate it with the element data.

Finding Out Information About a Ruby Array

Once an array exists, it can be useful to find out information about that array and its elements. As we mentioned earlier, it is possible to find out if an array is empty or not:

days_of_week.empty?
=> true

We can also find out the size of an array using the size method of the Array class:

days_of_week = Array.new(7)
days_of_week.size
=> 7

We can also find out what type of object is contained in array by using the array index value of the element we want to interrogate combined with the class method:

days_of_week = [ "Mon", 15, "Wed", 16, "Thu", 17 ]

days_of_week[0].class
=> String

days_of_week[1].class
=> Fixnum

Accessing Array Elements

The elements of an array can be accessed by referencing the index of the element in question in conjunction with the [] method. Note that indexing starts at 0 and not one. To access the first and second elements of our array therefore:

days_of_week[0]
=> "Mon"

days_of_week[1]
=> "Tues"

The Array class at method can be used to similar effect:

days_of_week.at(0)
=> "Mon"

The last element of an array may be accessed by specifying an array index of -1. For example:

days_of_week[-1]
=> "Sun"

The first and last elements may be accessed by using the first and last methods of the Array class:

days_of_week.first
=> "Mon"

days_of_week.last
=> "Sun"

Finding the Index of an Element

Often when working with arrays it is necessary to find out the index of a particular element. This can be achieved using the index method which returns the index of the first element to match the specified criteria. For example, to identify the index value of the "Wed" element of our days of the week array:

days_of_week.index("Wed")
=> 2

The rindex can be used to find the last matching element in an array.

A subset of an array's elements may be extracted by specifying the start point and the number of elements to extract. For example, to start at element 1 and read 3 elements:

days_of_week[1, 3]
=> ["Tues", "Wed", "Thu"]

Similarly, we can specify a range (for information on ranges see the Ruby Ranges chapter).

days_of_week[1..3]
=> ["Tues", "Wed", "Thu"]

Alternatively, the slice method of the Array class may be used:

 days_of_week.slice(1..3)
=> ["Tues", "Wed", "Thu"]