Class: TrickBag::Enumerables::EndlessLastEnumerable

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/trick_bag/enumerables/endless_last_enumerable.rb

Overview

Takes an enumerable or number as input. On successive calls to next, it returns the next element in the that enumerable until it has been exhausted, and then returns the last element every time it’s called. Especially useful in reading configuration files.

You can use Ruby’s array addition and multiplication features to provide rich functionality, e.g.:

array = [1] + [15]*3 + [60]*15 + [300]

Values should only be nonzero positive integers.

Why would this ever be useful? It was created for the benefit of a long running program, to provide time intervals for checking and reporting. It was helpful to report frequently at the beginning of the run, to give the user an opportunity to more easily verify correct behavior. Since the operations performed were potentially time consuming, we did not want to perform them frequently after the beginning of the run. For example, the array provided might have been [1] + [5] * 10 + [10] * 10 + [30].

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enumerable_or_number) ⇒ EndlessLastEnumerable

Returns a new instance of EndlessLastEnumerable.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/trick_bag/enumerables/endless_last_enumerable.rb', line 30

def initialize(enumerable_or_number)
  @inner_enumerable = case enumerable_or_number
    when Enumerable
     enumerable_or_number
    when Numeric
     Array(enumerable_or_number)
    else
     raise RuntimeError.new("Unsupported data type (#{enumerable_or_number.class}.")
    end
  @pos = 0
end

Instance Attribute Details

#inner_enumerableObject (readonly)

Returns the value of attribute inner_enumerable.



28
29
30
# File 'lib/trick_bag/enumerables/endless_last_enumerable.rb', line 28

def inner_enumerable
  @inner_enumerable
end

Instance Method Details

#==(other) ⇒ Object

mostly for testing



58
59
60
# File 'lib/trick_bag/enumerables/endless_last_enumerable.rb', line 58

def ==(other)   # mostly for testing
  other.is_a?(self.class) && other.inner_enumerable == inner_enumerable
end

#eachObject



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/trick_bag/enumerables/endless_last_enumerable.rb', line 43

def each
  return to_enum unless block_given?
  last_number = nil

  inner_enumerable.each do |number|
    yield(number)
    last_number = number
  end

  loop do
    yield(last_number)
  end
end