Advanced Ruby Arrays

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Understanding Ruby ArraysRuby Operators


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99


In the Understanding Ruby Arrays we looked at the basics of arrays in Ruby. In this chapter we will look at arrays in more detail.


Contents


Combining Ruby Arrays

Arrays in Ruby can be concatenated using a number of different approaches. One option is to simply add, them together:

days1 = ["Mon", "Tue", "Wed"]
days2 = ["Thu", "Fri", "Sat", "Sun"]
days = days1 + days2
=> ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

Alternatively, the concat method may be called:

days1 = ["Mon", "Tue", "Wed"]
days2 = ["Thu", "Fri", "Sat", "Sun"]
days = days1.concat(days2)

Elements may also be appended to an existing array using the << method. For example:

days1 = ["Mon", "Tue", "Wed"]
days1 << "Thu" << "Fri" << "Sat" << "Sun"
=> ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

Intersection, Union and Difference

Ruby's support for array manipulation goes beyond that offered by many other scripting languages. One area where this is particularly true involves the ability to create new arrays based on the union, intersection and difference of two arrays. These features are provided via the following set operation symbols:


OperatorDescription
-Difference - Returns a new array that is a copy of the first array with any items that also appear in second array removed.
&Intersection - Creates a new array from two existing arrays containing only elements that are common to both arrays. Duplicates are removed.
|Union - Concatenates two arrays. Duplicates are removed.


A few examples will help to clarify these operations. Let's begin by creating two arrays:

operating_systems = ["Fedora", "SuSE", "RHEL", "Windows", "MacOS"]

linux_systems = ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora"]

Now, we can create a union of the two arrays:

operating_systems | linux_systems
=> ["Fedora", "SuSE", "RHEL", "Windows", "MacOS", "PCLinuxOS", "Ubuntu"]

As we can see from the above output, the union operation joined one array to another, but removed any duplicate array elements.

Next we can perform an intersection:

operating_systems & linux_systems
=> ["Fedora", "SuSE", "RHEL"]

This time, we only get elements that are common to both arrays.

Finally, we can try a "difference" operation:

operating_systems - linux_systems
=> ["Windows", "MacOS"]

In this case, the new array provides us with the difference between the two arrays. In other words we get a new array that contains items which are present in operating systems, but not present in linux_systems. It is important to be clear on the point that we are not simply removing duplicate entries with this operator, but rather removing items from the array specified by the left hand operand that are also present in the array specified by the right hand operand. This can be demonstrated by the fact that switching the operands gives us very different results:

linux_systems - operating_systems
=> ["PCLinuxOS", "Ubuntu"]

Identifying Unique Array Elements

The uniq method of the Array class can be used to remove duplicated elements from an array. For example:

linux_systems = ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora", "RHEL", "SuSE"]

linux_systems.uniq
=> ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora"]

Note that in this instance, the original array is unchanged by the uniq method. If you really wanted to strip out the duplicates from an array such that the array itself is altered, use the uniq! method as follows:

linux_systems
=> ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora", "RHEL", "SuSE"]

linux_systems.uniq!
=> ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora"]

linux_systems
=> ["RHEL", "SuSE", "PCLinuxOS", "Ubuntu", "Fedora"]

Pushing and Popping Array Elements

An array in Ruby can be treated as a Last In First Out stack where items are pushed onto and popped off the array. This is achieved, unsurprisingly, using push and pop methods.

For example we can create an array and then push elements onto it:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]

colors.push "indigo"
=> ["red", "green", "blue", "indigo"]

colors.push "violet"
=> ["red", "green", "blue", "indigo", "violet"]

Using the pop method we can also pop elements from the array:

colors.pop
=> "violet"

colors.pop
=> "indigo"

Note how the elements are popped out of the array, starting with the last to be pushed onto it. Hence the term Last In First Out (LIFO).

Ruby Array Comparisons

Ruby arrays may be compared using the ==, <=> and eql? methods.

The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.

The eql? method is similar to the == method with the exception that the values in corresponding elements are of the same value type.

Finally, the <=> method (also known as the "spaceship" method) compares two arrays and returns 0 if the arrays are equal, -1 one if the elements are less than those in the other array, and 1 if they are greater.

Modifying Arrays

A new element may be inserted into an array using the insert method. This method takes as arguments the index value of the element to be inserted, followed by the new value. For example, to insert a new color between the red and green elements:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]

colors.insert( 1, "orange" )
=> ["red", "orange", "green", "blue"]

Any array element may be changed simply by assigning a new value using the array element index:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]=> ["red", "yellow", "blue"]

colors[1] = "yellow"
=> "yellow"

colors
=> ["red", "yellow", "blue"]

Multiple elements can be changed by making use of a range:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]

colors[1..2] = "orange", "pink"
=> ["orange", "pink"]

colors
=> ["red", "orange", "pink"]

Deleting Array Elements

It is not uncommon to need to delete individual elements from an array. A deletion can be performed either based on the content of an array element, or on the index position.

To delete based on an index use the delete_at method:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]

colors.delete_at(1)
=> "green"

colors
=> ["red", "blue"]

To delete array elements based on content use the delete method:

colors = ["red", "green", "blue"]
=> ["red", "green", "blue"]

colors.delete("red")
=> "red"

colors
=> ["green", "blue"]

Sorting Arrays

Arrays are sorted in Ruby using the sort and reverse methods:

numbers = [1, 4, 6, 7, 3, 2, 5]
=> [1, 4, 6, 7, 3, 2, 5]

numbers.sort
=> [1, 2, 3, 4, 5, 6, 7]

As with the uniq method, the sorting can be applied to the actual array with the sort! method.

The order of the elements in an array can be reversed using the reverse method:

numbers = [1, 4, 6, 7, 3, 2, 5]
=> [1, 4, 6, 7, 3, 2, 5]

numbers.sort!
=> [1, 2, 3, 4, 5, 6, 7]


numbers.reverse
=> [7, 6, 5, 4, 3, 2, 1]


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99



PreviousTable of ContentsNext
Understanding Ruby ArraysRuby Operators