Changes

Jump to: navigation, search

Understanding Ruby Arrays

998 bytes added, 20:19, 26 November 2007
Accessing Array Elements
days_of_week.last
=> "Sun"
</pre>
 
== 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:
 
<pre>
days_of_week.index("Wed")
=> 2
</pre>
 
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:
 
<pre>
days_of_week[1, 3]
=> ["Tues", "Wed", "Thu"]
</pre>
 
Similarly, we can specify a range (for information on ranges see the [[Ruby Ranges]] chapter).
 
<pre>
days_of_week[1..3]
=> ["Tues", "Wed", "Thu"]
</pre>
 
Alternatively, the ''slice'' method of the Array class may be used:
 
<pre> days_of_week.slice(1..3)
=> ["Tues", "Wed", "Thu"]
</pre>

Navigation menu