Enumerator

A quick way to create multiple Enumerables

The Enumerator class is a handy way to add multiple Enumerables to a class.

class Person
  def initialize
    @addresses = []
    @emails = []
  end

  # Here it is...
  def names
    Enumerator.new do
      @array.each do |person|
        it.yield person.name
      end
    end
  end

  def emails
    Enumerator.new do
      @array.each do |person|
        it.yield person.email
      end
    end
  end
end

Person.new.names.each do |name|
  puts name
end

Person.new.emails.each do |email|
  puts email
end

Enumerators are a powerful tool for iterating over collections of elements. They provide a simple and efficient way to iterate over a collection of elements, without having to worry about the underlying implementation details.

Do you want to learn Phlex 💪 and enjoy these code examples?

Support Beautiful Ruby by pre-ordering the Phlex on Rails video course.

Order the Phlex on Rails video course for $379 $289