Iterating in Ruby: 4 ways to go

The 4 different ways to iterate in Ruby

1. The Kernel#loop method

2. The control expressions

  • while..end
  • until..end
  • for..end

3. The Integer methods

  • Integer#times
  • Integer#upto
  • Integer#downto

4. The specific methods for collections

  • String#each_char
  • Array#each
  • Array#reverse_each
  • Enumerable#each_with_index
  • Enumerable#each_with_object
  • Hash#each or Hash#each_pair
  • Hash#each_key
  • Hash#each_value
  • Range#each

  • 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 the Kernel#loop 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 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.

Examples

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