Enumerable

Why are modules useful?

As its name explain it it a separate and individual part of the code, and here are three of the reasons why it is useful:

  • Because you can group together: Methods, Classes, and Constants. In a single module
  • It prevent a name space and prevent name clashes.
  • Modules implement the mixin facility.

What does #each do?

Calls the given block once for each element on it self. One example is to print the list of countries that I travel to:


What does #each return?

As you can see on the example above, it will pass the element as a parameter.


What does #map do?

This method takes an enumerable object and a block, and runs the block for each element, the original object is not change unless you use .map! for a better grasp of what this means see the code below.


What does #map return?

As you can see on the example, this will return the product of each element executed by the code on the block.


What does #select do? & What does #select return?

It takes an array and processed in a block with specific filters or rules coded on a block, it will return a new array containing all elements of the previous array for which the given block returns are true.

Now en English and with one example, Imagine that you have an array with number from 1..10 and you want to get those that are divisible by 2, in this example we will use the method .select to do just that.


What is the difference between #each #map and #select?

They are tools that do different things, when given the same array:

.each : will return each element of the array

.map : will process each element with some coded instructions and return the product.

.select : will filter each element to return those  that pass the coded requirements.



Copyright 2017. All rights reserved.

Posted December 12, 2016 by Edmundo in category "Daily