Difference between revisions of "Advanced Ruby Arrays"

From Techotopia
Jump to: navigation, search
(Combining Ruby Arrays)
(Intersection, Union and Difference)
Line 32: Line 32:
 
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:
 
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:
  
<table>
+
<table border="1" cellspacing="0">
 +
<tr style="background:#efefef;">
 
<th>Operator</th><th>Description</th>
 
<th>Operator</th><th>Description</th>
 
<tr>
 
<tr>

Revision as of 01:00, 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 with duplicate elements removed
&Intersection - Creates a new array containing only elements that are common to both arrays. Duplicates are removed.
|Union - Concatenates two arrays after removing duplicates