Class: ScanLeft

Inherits:
Object
  • Object
show all
Defined in:
lib/scan_left.rb,
lib/scan_left/version.rb

Overview

Wraps any Enumerable to provide the #scan_left operation.

Please see README for details, examples, background, and further reading about this operation.

Note: if you’d prefer to use the #scan_left method directly on any Enumerable instance, please see the optional refinement EnumerableWithScanLeft.

Examples:

ScanLeft.new([1, 2, 3]).scan_left(0) { |s, x| s + x } == [0, 1, 3, 6]

See Also:

Constant Summary collapse

VERSION =
"0.3.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enumerable) ⇒ ScanLeft

Returns a new instance of ScanLeft.

Parameters:

  • enumerable (Enumerable)

    Enumerable to transform via #scan_left



26
27
28
# File 'lib/scan_left.rb', line 26

def initialize(enumerable)
  @enumerable = enumerable
end

Instance Attribute Details

#enumerableEnumerable (readonly)

Returns Enumerable to transform via #scan_left.

Returns:

  • (Enumerable)

    Enumerable to transform via #scan_left



23
24
25
# File 'lib/scan_left.rb', line 23

def enumerable
  @enumerable
end

Instance Method Details

#scan_left(initial) {|memo, obj| ... } ⇒ Enumerable

Map the enumerable to the incremental state of a calculation by applying the given block, in turn, to each element and the previous state of the calculation, resulting in an enumerable of the state after each iteration.

Parameters:

  • initial (Object)

    Initial state value to yield.

Yields:

  • (memo, obj)

    Invokes given block with previous state value memo and next element of the stream obj.

Yield Returns:

  • (Object)

    The next state value for memo.

Returns:

  • (Enumerable)

    Generate a stream of intermediate states resulting from applying a binary operator. Equivalent to a stream of #inject calls on first N elements, increasing N from zero to the size of the stream. NOTE: Preserves laziness if enumerable is lazy.



47
48
49
50
51
# File 'lib/scan_left.rb', line 47

def scan_left(initial)
  memo = initial
  outs = enumerable.map { |*obj| memo = yield(memo, *obj) }
  prepend_preserving_laziness(value: initial, enum: outs)
end