Difference between revisions of "Advanced Ruby Arrays"

From Techotopia
Jump to: navigation, search
(Intersection, Union and Difference)
(Intersection, Union and Difference)
Line 36: Line 36:
 
<th>Operator</th><th>Description</th>
 
<th>Operator</th><th>Description</th>
 
<tr>
 
<tr>
<td>-</td><td>Difference - Creates a new array with duplicate elements removed</td>
+
<td align="center">-</td><td>Difference - Creates a new array from two existing arrays with duplicate elements removed</td>
 
<tr>
 
<tr>
<td>&</td><td>Intersection - Creates a new array containing only elements that are common to both arrays.  Duplicates are removed.</td>
+
<td>&</td><td>Intersection - Creates a new array from two existing arrays containing only elements that are common to both arrays.  Duplicates are removed.</td>
 
<tr>
 
<tr>
 
<td>|</td><td>Union - Concatenates two arrays after removing duplicates</td>
 
<td>|</td><td>Union - Concatenates two arrays after removing duplicates</td>
 
</table>
 
</table>

Revision as of 01:02, 27 November 2007

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