DEV Community

Yong Liang
Yong Liang

Posted on

Ruby: Different types of iterators

Overview

When we have a collection of data (an array for example), we can use iterators to operate each member of that collection and get the return value(s) we want. Let's take a look at some commonly used iterators in Ruby and their return values.

.each

The .each iterator returns the original data structure that it operated on, despite the fact that we modified values in the block. However, we could have another variable to hold the changes inside the block.

.map or .collect

The way .map or .collect iterates is similar to .each, but will return the new/modified data structure instead of the original one.

.select

With the .select iterator, we set a condition inside the block and it returns a new data structure with values that are true to that condition. It filters out the one that are false.

.find

The .find works similar to .select, however, it return the value as soon as the condition is met/true.

Top comments (0)