Enumerators in Ruby
Enumerators are a set of methods to traverse, search, sort and manipulate collections (Lists and Hashes) in Ruby.
The concepts regarding enumerators are directly related with loops and collections. If you understand the concepts of loops, lists and hashes, there is absolutely nothing new conceptually in this post. Usually, Enumerators allow us to write more elegant solutions with fewer lines of code.
EACH
The Each
method yields each element from the collection that is calling it to the block passed as argument. This method returns the original version collection, no mater what operations you applied to each element.
MAP
The Map
method yields each element from the collection that is calling it to the block passed as argument. This method returns the modified version of the collection.
COLLECT
The Collect
method is just an alias for the Map
method.
INJECT
The Inject
method takes an accumulator (sum
in the example below) and iterate through each element doing operations with them. This method returns the accumulator when it is done.
In the example below we use the accumulator to hold the sum of all elements of the shopping_cart
list.
REDUCE
The Reduce
method is just an alias for the Inject
method. We can also pass an initial value for the accumulator, default is 0.
SELECT
The Select
method returns a list with all elements that matches the condition passed in the block. In this example it is going to return a list with all even numbers from the list.
REJECT
The Reject
method is exactly the opposite of the method Select
; It returns a list with all elements that does not match the condition passed in the block.
In the example below it is going to return a list with all odd numbers from the list. We are reject
ing all the even numbers.
FIND
The Find
method returns the first element in the collection that matches the condition passed in the block. It returns nil
if there is no element that matches the condition.
DETECT
The Detect
method is just an alias for the Find
method.
Enumerators are a great feature in the Ruby language. It makes it easier to work with collections. I hope you liked this post and I am looking forward to writing the next one.