Module 26 Β· Enumerable, Enumerator & Pattern Matching β Lesson 1 of 6 Β· ~8 min
The Enumerable Contract
One method in, fifty methods out
Enumerable is the best deal in Ruby. Define one method β each β include Enumerable, and your class instantly gains map, select, reject, find, sort_by, group_by, sum, min_by, count, to_a, and ~40 more. All of them are implemented once, in the module, in terms of the each you wrote. This is the ancestor chain (module 24) paying off: Enumerable sits in your class's lookup path and every method drives your each.
In an interview, say: "
Enumerableis a mixin that builds ~50 collection methods on top of a singleeach. Any class that can iterate caninclude Enumerableand get the whole query vocabulary for free β that's howArray,Hash,Range, and ActiveRecord relations all share the same API."