Ruby Iterators

Evelyn Hernandez
3 min readNov 8, 2020

During my time as a Flatiron Student, I’ve learned so many things that I never thought I’d be capable of comprehending. I can make a whole series of blogs of all things that cause me confusion, but you’d be here for a while. So, let’s just skip to iterators! Did you see that super smooth transition I just made? Yeah me either, anyways!! I’ve struggled with when to use them? How do they work? I’m so confused! What am I doing?! I’m joking about that last part. Okay, I’m not but you get the point.

Let’s break this down, iterators are methods supported by collections. Collections are objects that store a group of data members. In Ruby, arrays and hashes are termed, collections. I wont go into detail on hashes and arrays, but below I have linked a blog that might help if you need a better understanding .

.each

The first to hit the spotlight is the most known, the cool kid, the MVP! Give it up for the each iterator!! The each iterator evaluates a block, but throws away the result of that evaluation and returns the original array. So when the evaluations are the most important part of your code, .each is your guy.

.each example using irb

.select

The select iterator allows us to select specific elements from the original collection, if the element is true, that element gets added to the collection returned. If false the element will be removed from the collection returned. In other words, it returns more than 1 element. You can use .select with arrays and hashes meaning that if you use .select with an array, it will return an array. Otherwise, if you use a hash, the return value will be a hash. Ba-da-bing Ba-da-boom!

.select example irb

.find

The find iterator takes an expression and returns the first element for which the element returns true. Its useful when you’re searching for one specific element in the collection. KNOW WHAT YOU’RE SEARCHING FOR! I cant express this enough. The select iterator is similar to .find. So DON’T do what I did!! Various times i’ve used .select when all I needed to do was keep it simple and use find. Remember we are lazy! We must live up to lazy expectations!

.find example using irb

.map/.collect

I put these two together because they are the same iterator! They both return new arrays constructed as the result of calling the block for each items in the array element. So, use this iterator when you want to generate a new array based on an existing array, but don’t want to change the initial object.

--

--

Evelyn Hernandez

I’m a FrontEnd Dev that enjoys learning & failing. With every unknown adventure comes failure, but only those who dare to fail greatly can ever achieve greatly.