DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›