The 4 different ways to iterate in Ruby
1. The Kernel#loop method
2. The control expressions
3. The Integer methods
4. The specific methods for collections
- Array#each, Hash#each, Range#each
- Enumerable#reverse_each, Array#reverse_each
- Hash#each_pair, Hash#each_key, Hash#each_value
- The Kernel#loop method is the tank method. It destroys everything on its way. You can always work your way to a working solution with this method, as long as you break properly.
- When you use a control expression or the Kernel#loop method to iterate through the elements of a specific collection, you usually need to initialize a "counter" local variable. This local variable is needed to track the number of iterations executed, either by adding or substracting units.
- The Integer methods are my favorite ones, because they do not need the initialization of a "counter" local variable. Also, I find them more natural to think with, especially when we have to build interdependent iterations. For example, to write a method that lists all substrings of a string, my favorite way to go is with the Integer#upto method.
- Whatever option you choose to iterate with, you can modify how the iterations are executed by using Ruby's keywords: break, return, next.
- The Enumerable methods are methods that are available to Enumerable collections. An Enumerable collection is a collection that has a #each method implemented in its Class. Enumerable methods can be used on Arrays, Hashes and Ranges.
- I did not include the Enumerable#map in the previous list because it is an iterating and transforming method. If you just need to iterate through a collection without transforming its elements, there is no need to use the Enumerable#map method.
Let's consider the following exercise: given the array below, turn this array into a hash where the animals are the keys and the values are the positions in the array.
animals = ['Dog', 'Cat', 'Mouse', 'Flamingo', 'Crocodile', 'Elephant']
With this exercise, we can use the 4 types of iterations. Let's go for a ride through 10 examples of code.
1. The Kernel#loop method
2. Control expression: while..end
3. Control expression: until..end
4. Control expression: for..end
5. Integer method: Integer#times
6. Integer method: Integer#upto
7. Integer method: Integer#downto (Not the natural way to go for this exercise)
8. Specific method for collections: Array#each
9. Specific method for collections: Enumerable#each_with_index
10. Specific method for collections: Enumerable#each_with_object
Initial publication date: 2018-07-03
Last updated: 2019-08-20