Ruby Language Implementation in a class


Example

Enumerable is the most popular module in Ruby. Its purpose is to provide you with iterable methods like map, select, reduce, etc. Classes that use Enumerable include Array, Hash, Range. To use it, you have to include Enumerable and implement each.

class NaturalNumbers
  include Enumerable

  def initialize(upper_limit)
    @upper_limit = upper_limit
  end

  def each(&block)
    0.upto(@upper_limit).each(&block)
  end
end

n = NaturalNumbers.new(6)

n.reduce(:+)                   # => 21
n.select(&:even?)              # => [0, 2, 4, 6]
n.map { |number| number ** 2 } # => [0, 1, 4, 9, 16, 25, 36]