Class: Iterator

Inherits:
Enumerator show all
Defined in:
lib/mug/iterator.rb

Overview

Note:

Similar to Enumerator.produce (Ruby 2.7+), but Enumerator.produce includes the initial value in its output.

A special class of Enumerator that repeatedly yields values to a block.

The initial yielded value is given in the constructor, but in subsequent iterations the result of the previous iteration is yielded.

Examples:

require 'mug/iterator/for'
0.iter_for(:next).take(5) #=> [1,2,3,4,5]

Instance Method Summary collapse

Methods inherited from Enumerator

#to_b, unfold

Constructor Details

#initialize(obj, *args) {|current, *args| ... } ⇒ Iterator

Creates a new Iterator object, which can be used as an Enumerable.

In the first form, iteration is defined by the given block, to which the current object and any other args are yielded.

In the second, deprecated, form, a generated Iterator sends the given method with any args to the iterand.

Use of this form is discouraged. Use Object#iter_for or Method#to_iter instead.

@call-seq new(initial, *args) { |obj, *args| ... } @call-seq new(initial, method=:each, *args)

Examples:

Block form

require 'mug/iterator'
Iterator.new(1) { |n| n * 2 }.take(5) #=> [2, 4, 8, 16, 32]

Parameters:

  • obj (Object)

    the initial value for iteration

  • args (Array)

    additional arguments passed to the block or method

Yields:

  • (current, *args)

    block defining the iteration logic

Yield Parameters:

  • current (Object)

    the current iteration value

Yield Returns:

  • (Object)

    the next iteration value



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mug/iterator.rb', line 45

def initialize obj, *args
  if block_given?
    super() do |y|
      loop do
        y << (obj = yield obj, *args)
      end
    end
  else
    warn 'Iterator.new without a block is deprecated; use Object#to_iter'
    args = [:each] if args.empty?
    super() do |y|
      loop do
        y << (obj = obj.send(*args))
      end
    end
  end
end