Turning several Enumerables into one

Viewed 104

Is there a way to get several Enumerable objects to appear as a single Enumerable without flattening it into an Array? Currently I've written a class like so, but I feel there must be a built-in solution.

class Enumerables
  include Enumerable

  def initialize
    @enums = []
  end

  def <<(enum)
    @enums << enum
  end

  def each(&block)
    if block_given?
      @enums.each { |enum|
        puts "Enumerating #{enum}"
        enum.each(&block)
      }
    else
      to_enum(:each)
    end
  end
end

enums = Enumerables.new
enums << 1.upto(3)
enums << 5.upto(8)
enums.each { |s| puts s }

As a simple example, it needs to be able to accept an infinite enumerator like so.

inf = Enumerator.new { |y| a = 1; loop { y << a; a +=1 } };
3 Answers

Well, it might be done with standard library using Enumerator. The advantage of this approach would be it returns the real enumerator, that might be mapped, reduced etc.

MULTI_ENUM = lambda do |*input|
  # dup is needed here to prevent
  #  a mutation of inputs when given
  #  as a splatted param
  # (due to `input.shift` below)
  input = input.dup.map(&:to_enum)
  Enumerator.new do |yielder|
    loop do
      # check if the `next` is presented
      #  and mutate the input swiping out
      #  the first (already iterated) elem
      input.first.peek rescue input.shift
      # stop iteration if there is no input left
      raise StopIteration if input.empty?
      # extract the next element from 
      #  the currently iterated enum and
      #  append it to our new Enumerator
      yielder << input.first.next
    end
  end
end

MULTI_ENUM.(1..3, 4.upto(5), [6, 7]).
  map { |e| e ** 2 }

#⇒ [1, 4, 9, 16, 25, 36, 49]

After all. Use Enumerable::Lazy#flat_map with .each.lazy on elements:

inf = Enumerator.new { |y| a = 1; loop { y << a; a += 1 } }
[(1..3).to_a, inf].lazy.flat_map { |e| e.each.lazy }.take(10).force
#⇒ [1, 2, 3, 1, 2, 3, 4, 5, 6, 7]

I ended up with this solution, maybe is close to what you already tried:

def enumerate(*enum)
  enum.each_with_object([]) { |e, arr| arr << e.to_a }.flatten
end

enumerate( 1..3, 5.upto(8), 3.times, 'a'..'c' ).each { |e| p e }

# => 1, 2, 3, 5, 6, 7, 8, 0, 1, 2, "a", "b", "c"

Or (same mechanics):

def enumerate(*enum)
  enum.flat_map { |e| e.to_a }
end
Related