Class: Jinx::MultiEnumerator

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Collection
Defined in:
lib/jinx/helpers/multi_enumerator.rb

Overview

A MultiEnumerator iterates over several Enumerators in sequence. Unlike Array#+, MultiEnumerator reflects changes to the underlying enumerators.

Examples:

a = [1, 2]
b = [4, 5]
ab = MultiEnumerator.new(a, b)
ab.to_a #=> [1, 2, 4, 5]
a << 3; b << 6; ab.to_a #=> [1, 2, 3, 4, 5, 6]
MultiEnumerator.new(ab, [7]).to_a #=> [1, 2, 3, 4, 5, 6, 7]

Instance Method Summary collapse

Methods included from Enumerable

#enumerate, #pp_s, #pretty_print, #pretty_print_cycle, #qp, #to_enum, #transitive_closure

Methods included from Collection

#compact, #compact_map, #detect_value, #detect_with_value, #difference, #empty?, #filter, #first, #flatten, #hashify, #intersect, #join, #last, #partial_sort, #partial_sort!, #partial_sort_by, #size, #to_compact_hash, #to_compact_hash_with_index, #to_series, #transform, #union

Constructor Details

#initialize(*enums) {|item| ... } ⇒ MultiEnumerator

Initializes a new Jinx::MultiEnumerator on the given components.

Parameters:

  • the (<Enumerable>)

    component enumerators to compose

Yields:

  • (item)

    the optional appender block

Yield Parameters:

  • item

    the item to append



22
23
24
25
26
27
# File 'lib/jinx/helpers/multi_enumerator.rb', line 22

def initialize(*enums, &appender)
  super()
  @components = enums
  @components.compact!
  @appender = appender
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object

Returns the union of the results of calling the given method symbol on each component.



43
44
45
# File 'lib/jinx/helpers/multi_enumerator.rb', line 43

def method_missing(symbol, *args)
  self.class.new(@components.map { |enum|enum.send(symbol, *args) })
end

Instance Method Details

#<<(item) ⇒ Object

Parameters:

  • item

    the item to append

Raises:



38
39
40
# File 'lib/jinx/helpers/multi_enumerator.rb', line 38

def <<(item)
  @appender ? @appender << item : super
end

#eachObject

Iterates over each of this MultiEnumerator’s enumerators in sequence.



30
31
32
33
34
# File 'lib/jinx/helpers/multi_enumerator.rb', line 30

def each
  @components.each do |enum|
    enum.each { |item| yield item }
  end
end