3

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)
Community
  • 1
  • 1
Jonah
  • 15,806
  • 22
  • 87
  • 161

2 Answers2

2

You can define a new enumerator, iterating through your existing enumerators. Something like:

enum = Enumerator.new { |y|
  enum1.each { |e| y << e }
  enum2.each { |e| y << e }
}
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
  • 1
    @Jonah Within `enum` you can combine the enumerators into an array and iterate through them as per Spiro's answer or like Cary's deleted answer. Or something like `[enum1,enum2].each { |e| e.each { |i| y << i } }` will work. – Sagar Pandya Sep 17 '17 at 04:40
1

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)
TeWu
  • 5,928
  • 2
  • 22
  • 36