I’m sure like most people, I started learning Rails by reading about….Rails. It would seem logical to learn Rails by reading about Rails, right? I think a better way of learning about Rails is to first master Ruby and THEN learn the Rails framework for Ruby. This approach has helped me debug some of those error messages that seemed so cryptic at first. Recently I picked up “Programming Ruby” by The Pragmatic Programmers. Reading it I found out that some of methods that I thought were part of the Rails framework actually belong to Ruby.
One of the things I wanted to focus on are the differences between three different types of iterators in Ruby that are commonly used in Rails: find, each, and collect. Let’s first start by asking what is an iterator? An iterator goes through each element in an array or hash table and let’s us perform an action using the individual element. Let’s check out the differences between these iterators.
find
Find is a bit misleading. The classical definition of a find method would be to return the index of the element (or perhaps the entire element itself) that matches a string. The find iterator method in ruby will instead compare each element using some comparison operator (<, >, ==, etc.) and based off of the boolean result (true or false), it will return the first matching value. For example say we have an array called a:
a = [ 1, 2, 3, 4, 5 ]
Using this array we want to find the first even value. Our code would look something like this:
a.find { |n| n % 2 == 0 }
Since 2 is the first even number, that would be the result.
each
Each is the simplest iterator method of the three. It simply traverses all elements in the array and returns each one individually. So if we want to print all lements of the array a, it would look something like this:
a.each { |n| print n }
The result would look like 12345
collect
Collect, or also known as map, is pretty much the same as each, except that collect returns an array of values. For this example, we’ll increment each element in array a and save the new element in b.
b = a.collect { |n| n + 1 }
This returns the array [2, 3, 4, 5, 6]
I hope this gives some insight on how Rails uses these methods.


Leave a Reply