Class: Enumerator::ArithmeticSequence

Inherits:
Object
  • Object
show all
Defined in:
lib/carray/basics.rb

Overview

Reopened to add #to_ca, so a stepped sequence can be handed to any CArray entry point that coerces its operand.

Instance Method Summary collapse

Instance Method Details

#to_ca(writable: false) ⇒ CArray

Returns the members of self as a 1-D CA_OBJECT CArray, so that a strided axis can be written (0..10).step(2) or (0.0..1.0).step(0.25).

An endless sequence is rejected up front: unlike an endless Range, which RangeErrors, enumerating one runs forever. As with Range#to_ca, descending integer bounds count down rather than coming back empty.

As with Array#to_ca the result is newly built, so writable: true is refused.

Returns:

Raises:

  • (RangeError)

    when the sequence has no end.

  • (RuntimeError)

    when writable: true is given.



467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/carray/basics.rb', line 467

def to_ca(writable: false)
  if writable
    raise "#{self.class}#to_ca builds a new array; " \
          "it can't satisfy `writable: true'"
  end
  first, last, by = self.begin, self.end, self.step
  if last.nil?
    raise RangeError, "cannot convert endless arithmetic sequence to an array"
  end
  if first.is_a?(Integer) and last.is_a?(Integer) and by > 0 and first > last
    return CA_OBJECT(Range.new(first, last, exclude_end?), by)
  end
  return CA_OBJECT(to_a)
end