The Enumerable Module is a mixin. The methods from the module are used in the Array and Hash classes. You can actually use the Enumerable module in any of your classes as long as you have
#each defined. All the methods in the module create a new data structure - ex: an array or hash - and the old one is not mutated. You would want to use the methods from the Enumerable module when you are iterating through a collection of objects and manipulating the data in that collection.
Lets say we want an array of shortened words
We can shorten the length of
#shorten by calling
#map from the Enumerable module
This method applies the block (what’s in the parenthesis) to each element in the original array and returns a new array (the original array is untouched)
Here are a few other useful methods from the Enumerable module
This method only keeps the elements that evaluate to true
This method aggregates values based on the operation passed in the block. The value passed into
#reduce is the starting value of the aggregation
#reduce is doing this
If no value is passed into
#reduce it will automatically start with 0.
Subscribe via RSS