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
- Hash#each or Hash#each_pair
Kernel#loopmethod is the tank method. It destroys everything on its way. You can always work your way to a working solution with the
Kernel#loopmethod, as long as you break properly.
- When you use a control expression or the
Kernel#loopmethod to iterate through the elements of a specific collection, you 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.
Integermethods 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
- Whatever option you choose to iterate with, you can modify how the iterations are executed by using Ruby's keywords:
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.