Advanced Ruby Arrays

Revision as of 01:02, 27 November 2007 by Neil (Talk | contribs) (Intersection, Union and Difference)

Revision as of 01:02, 27 November 2007 by Neil (Talk | contribs) (Intersection, Union and Difference)

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.

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 - Creates a new array from two existing arrays with duplicate elements 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 after removing duplicates