Ruby Language Iteration Implementation in a class

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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]


Got any Ruby Language Question?