This week's cirriculum emphasized the use of Enumerators in Ruby. Enumerators are a set of methods contained within the Enumerable module, which enables us to use the aforementioned methods on unrelated classes. In order to use the Enumerators, however, a class must have a defined each method. For those that do, the Enumerators allow us to sort, search, append, and manipulate a collection within a particular class, such as Array. For a couple problems this week, I relied heavily on the Enumerator map, which invokes a given block of code for each element (x) and returns a new array (new_ary):
map {|x| block} -> new_ary
As an example, let's define the following array:
array = [3,"pizza", "bagels", "are", "good", "but",4, "would", "be", "awesome"]
Now, for the array above, let's say we want to return a new array that adds some number n to the integer elements in the original array. We can use map to do this:
def array_add_integer(array,n)
array.map {|x| x.is_a?(Integer)? x + n : x}
end
For the each element in the array, map is running the code block x.is_a?(Integer)? x + n : x and returning a new array. For array_add_integer(array,3), we get:
[6, "pizza", "bagels", "are", "good", "but", 7, "would", "be", "awesome"]
It's important to note that the original array has not been modified. The output is a completely new array. Calling the original array will give the original elements as an output. This makes map non-destructive, since the original array was not modified when we ran the method array_add_integer.
As mentioned earlier, the Enumerable module allows us to use Enumerators on unrelated classes. So far, we've shown how map can be used for Array; however, it can also be used on the class Range:
(1..10).map {|x| x*x } => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
I tend to think of map like this: it's a useful enumerator for executing the same action across particular elements in a collection of data, without comprimising the integrity of the original data set. Perhaps that's an an over-simplification, but it is super useful.