Common Iterators in Ruby


Internal Iterators are very important in Ruby because the allow us to return a wide variety of specific values when iterating through an array.

The following methods (iterators) are very common in Ruby:

.each = iterate but it does not return a value after running the code.

.select = iterate and return a subset of that collection based on certain criteria. It creates a new array taking some values from the old array.

.map = iterate and creates a altered version of the array. It creates another array with the same number of values.

.reduce = iterate and keeps every value, transforming it into a total value. This single value can also be a array. Each iteration starts with the return value of the previous one. That means it takes a collection of values, starts with the first value, apply a function to that first value, keeps the result, takes the second value, apply the function to that second value, adds the result of that second operation to the result of the previous one, and so on, until it comes up with a total value.

I hope this helps you decide better on which method to use when iterating through an array in Ruby.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s