Working with Collections in Ruby
- Slicing an Array
- Iterating over an Array
- Creating Enumerable Classes
- Sorting an Array
- Iterating over Nested Arrays
- Modifying All the Values in an Array
- Sorting Nested Arrays
- Building a Hash from a Config File
- Sorting a Hash by Key or Value
- Eliminating Duplicate Data from Arrays (Sets)
- Working with Nested Sets
In Ruby and other dynamic languages, “Collection” is an umbrella term for general-use lists and hashes. The ease of working with these data structures is an attractive feature and one that often contributes to making prototyping in Ruby a pleasurable experience. The implementation details of lists and hashes and their underlying mechanisms are mostly hidden from the programmer leaving him to focus on his work.
As you browse this section, keep in mind that underpinning everything you see here are traditional C-based implementations of lists and hashes; Ruby is attempting to save you the trouble of working with C—but be sure, that trouble saving can come at performance cost.
Slicing an Array
This section has a lot of analogs to the earlier section “String to Array and Back Again,” in Chapter 1, “Converting Between Types.” You can slice an Array a number of ways:
[1, 2, 3, 4, 5, 6, 7, 8, 9][4] #=> 5 (a Fixnum object) [1, 2, 3, 4, 5, 6, 7, 8, 9][4,1] #=> [5] (single element Array) [1, 2, 3, 4, 5, 6, 7, 8, 9][4,2] #=> [5, 6] [1, 2, 3, 4, 5, 6, 7, 8, 9][-4,4] #=> [6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9][2..5] #=> [3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7, 8, 9][-4..-1] #=> [6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9][2...5] #=> [3, 4, 5] [1, 2, 3, 4, 5, 6, 7, 8, 9][-4...-1] #=> [6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8, 9][4..200] #=> [5, 6, 7, 8, 9] (no out of range error!)
Array Ranges |
Positions (Counting Starts at 0, Negative Numbers Count Position from the End) |
A[{start}..{end}] |
{start} includes the element; {end} includes the element |
A[{start}...{end}] |
{start} includes the element; {end} excludes the element |
A[{start}, {count}] |
{start} includes the element; {count} positions from start to include |
You might also like to select elements from the Array if certain criteria are met:
[1, 2, 3, 4, 5, 6, 7, 8, 9].select { |element| element % 2 == 0 } #=> [2, 4, 6, 8] (all the even elements)