Built in way to concatenate two Enumerators

Viewed 1900

Say you have:

enum1 = 1.upto(5)
enum2 = 7.upto(10)

I want:

enum_combined = enum1.some_method(enum2)

such that:

enum_combined.to_a #=> [1, 2, 3, 4, 5, 7, 8, 9, 10]

I don't see any method on the Enumerator class that would do this, but before rolling my own solution I'd like make sure I'm not missing some built-in way to do this.

To be clear: I want the returned result to be another Enumerator object, since I want the entire calculation to be lazy.

UPDATE

Per the linked duplicate, the way to achieve this is:

combined = [enum1, enum2].lazy.flat_map(&:lazy)
2 Answers

You can make Enumerator class extension like this:

class Enumerator
  def self.concat(*enumerators)
    self.new do |y|
      enumerators.each do |e|
        e.each {|x| y << x }
      end
    end
  end
end

and use it like that:

enum3 = Enumerator.concat(enum1, enum2)
Related