Ruby – For vs Each

In Ruby, both ways of iterating through a collection are valid and will produce the same result. However, there are some differences between them.

The first way you mentioned is using the each method along with a block. This is the more commonly used and idiomatic way of iterating through collections in Ruby. It is known as an iterator. The each method is available on most collection objects and allows you to perform a specific action on each element of the collection. The block, which is denoted by do…end or {}, contains the code that will be executed for each item in the collection.

Apart from the difference in style and idiomatic usage, there are a few other differences between the each method and the for loop in Ruby:

When using each with a block, the block has its own scope. Variables defined within the block are local to the block and cannot be accessed outside of it. This can help prevent variable conflicts and make your code more organized. On the other hand, the for loop does not create a new scope. Variables assigned within the loop are accessible outside of it.

Return Value
The each method returns the original collection after iteration, which allows for method chaining. For example, you can chain other methods after each to further process the collection. The for loop does not have a return value, so it cannot be used in a chain like that.

In terms of performance, the each method is generally faster and more efficient than the for loop. This is because the each method is implemented using internal iteration, which is optimized in Ruby. The for loop, on the other hand, relies on external iteration and creates a new variable for each iteration.

Given these differences, the each method is usually preferred in Ruby code due to its readability, flexibility, and performance benefits. It aligns with Ruby’s philosophy of providing elegant and expressive ways to work with collections.

Subscribe for
weekly updates