- 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
Iterating over an Array
This is one of the joys of Ruby. It’s so easy!
You can also do the trusty old for loop:
for element in [1, 2, 3, 4, 5] # do something to element end
The difference between a for loop and an #each is that in for, a new lexical scoping is not created. That is, any variables that are created by for or that are in the loop remain after the loop ends.
To traverse the Array in reverse, you can simply use #Arrayreverse#each. Note that in this case, a copy of the Array is being made by #reverse, and then #each is called on that copy. If your Array is very large, this could be a problem.
In order for you get any more specialized than that, however, you need to work with the Enumerator module. For example, you might want to traverse an Array processing five elements at a time as opposed to the one element yielded by #each:
require 'enumerator' ary = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ary.each_slice(5) { |element| p element } Outputs: [0, 1, 2, 3, 4] [5, 6, 7, 8, 9]