Enumerable (Ruby)

Enumerable is a Ruby module that provides dozens of collection methods — map, select, reduce, sort, find, and more — to any class that defines an each method. Array and Hash include it.

Ruby

Enumerable is the engine behind Ruby's powerful collection operations. A class only needs to define each; by including Enumerable it instantly gains map, select, reject, reduce/inject, find, all?, any?, count, sort_by, group_by, min, max, and many others — all built on top of each.

Array, Hash, Range, and Set all include Enumerable, which is why the same fluent methods work across them. You can give your own collection class the whole toolkit just by defining each and including the module.

These methods chain to express data transformations declaratively: list.select { ... }.map { ... }.sort. Knowing Enumerable well is the difference between writing manual loops and writing concise, idiomatic Ruby.

Syntax

class MyList
  include Enumerable
  def each; ...; end
end

Examples

Ruby

nums = [3, 1, 4, 1, 5]
puts nums.select(&:even?).inspect
puts nums.sort.inspect
puts nums.group_by { |n| n.odd? ? :odd : :even }.inspect

Output:

[4]
[1, 1, 3, 4, 5]
{:odd=>[3, 1, 1, 5], :even=>[4]}

Learn it in a lesson

See also

Back to the Dictionary