An Enumerator is a class which allows both internal and external iteration. Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration.
In other words, such cool tools to master! I’m going to break down the basic ones that I’ve been using recently.
Boolean Enumerators:
#all? - the block passed to it must return true for every iteration
#none? – the block returns false for every iteration
#any? – will return true if at least one iteration of the block evaluates to true, but false if none of them do.
#include? – will return true if the given object exists in the element. If it doesn’t find a match, it will return false.
Search Enumerators:
#select - return value will be a new array containing all the elements of the collection that cause the block passed to #select to return true
#detect or #find - only return first element that makes block true
#reject - return an array with the elements for which the block is false
#sort – yields to a block with two elements, that block is the comparator
The <=> symbol is called the combined comparison operator.
- Returns 0 if first operand equals the second
- Returns -1 if the first operand is less than the second
- Returns 1 if first operand is greater than the second
To kind of break down what the #sort method does, it looks like this in its full glory:
Which can be condensed into this:
So hopefully that gives you a quick understanding of how all of those enumerators work. They’re a pretty powerful tool to use in your code which makes it important to really grasp these concepts.
For more info on Enumerators: https://docs.ruby-lang.org/en/2.0.0/Enumerable.html