Archaic Positives

Adventurer, Traveler, Rubyist

Difference Between Each, Select, and Collect Methods

Each, Collect, Select

There are three methods that drive the process of data scraping and warehousing in the Ruby language. These three methods are the following: Each, Collect, and Select. These three methods are examplees of iterators; iterators are used to organize and store data into a collection. A collection can be either an array or a hash.

For simplicity, I will refer to an array throughout the rest of the discussion. I`ll follow up with a concise post on hashes.

The Each method iterates through and returns all of the elements of an array or a hash. It simply runs each element of the array through the Each code block (the function/modifier that lies between the do and end), and returns that modified value to the console. For example:

array = [2,4,6,8,10] array.each { |x| puts x * 10 }

This would result in the following being output to the screen:

20, 40, 60, 80, 100

The Each method is great for simple data modification tasks, particularly if you need to obtain the result of that modification. The major drawback is that it doesn`t provide a means to store the results of the block into an array unless you push those elements into the array. This is where the Collect method comes in.

The Collect method does the same thing as the Each method, except that it goes one step further and returns the results of the block in the form of an array. For instance, look at the following example.

array = [2,4,6,8,10] array.collect { |x| x * 10 }

This would result in the following output to the screen:


The array “array” has been multiplied by the modifier inside of the block, and the collect method has returned an array with the modified values. The returned array can then be stored in a variable, which has significant benefits in Ruby. This can be used for many applications, such as arithmetic, problem solving, variable manipulation, and data parsing.

The Select method is a modified version of the Each method, and basically “selects” objects that meet the predefined condition within the block. For example, if I wanted to filter out elements from an array that do not meet a conditional statement of some kind, I could do the following:

array = [1,2,3,4,5] { |x| x > 2 }

It would return the following to my screen:


It basically will return any element of the array that, when inserted into the conditional statement inside of the block, results in a true statement.

These three statements are already some of my most heavily used components within my Ruby syntax. I’m still learning each day more and more about what they are capable of. I’m excited to learn more about more specific applications of these methods.