Sha256: cc7436d34a62e8e3452056002fb107c4f55239feee3b09d3f983d5b294355e56

Contents?: true

Size: 1.97 KB

Versions: 3

Compression:

Stored size: 1.97 KB

Contents

# -*- encoding: utf-8 -*-

module TTY

  # This class represents a mathematical vector.
  class Vector
    include Enumerable, Equatable, Conversion

    attr_reader :elements
    protected :elements

    # Utility method to instantiate a Vector
    #
    # @param [Array] *array
    #
    # @return [Vector]
    #
    # @api public
    def self.[](*array)
      new convert_to_array(array)
    end

    # Instantiate a Vector
    #
    # @param [Array] array
    #
    # @return [undefined]
    #
    # @api public
    def initialize(array=[])
      @elements = convert_to_array(array)
    end

    # Return element at index.
    #
    # @param [Integer] indx
    #   index of an element
    #
    # @return [Object]
    #   a value of an element
    #
    # @api public
    def [](indx)
      elements[i]
    end
    alias at      []
    alias element []

    # Set a value of the element for the given index.
    #
    # @param [Integer] indx
    #   an index of an element
    #
    # @param [Object] value
    #   a value to be set
    #
    # @return [Object]
    #
    # @api public
    def []=(indx, value)
      elements[index] = value
    end
    alias set_element []=

    # Iterate over each element in the vector
    #
    # @example
    #   vec = Vector[1,2,3]
    #   vec.each { |element| ... }
    #
    # @return [self]
    #
    # @api public
    def each(&block)
      return to_enum(:each) unless block_given?
      to_ary.each(&block)
      self
    end

    # Convert to array
    #
    #  @return [Array]
    #
    # @api public
    def to_ary
      elements
    end

    # Check if there are not elements.
    #
    # @return [Boolean]
    #
    # @api public
    def empty?
      to_ary.empty?
    end

    # Check number of elements.
    #
    # @return [Integer]
    #
    # @api public
    def size
      to_ary.size
    end

    # Return the vector elements in an array.
    #
    # @return [Array]
    #
    # @api public
    def to_a
      elements.dup
    end

  end # Vector
end # TTY

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tty-0.0.7 lib/tty/vector.rb
tty-0.0.6 lib/tty/vector.rb
tty-0.0.5 lib/tty/vector.rb