class EasyGeometry::D2::Vector

A vector in a 2-dimensional Euclidean space.

Constants

EQUITY_TOLERANCE

Attributes

x[R]
y[R]

Public Class Methods

new(x, y) click to toggle source
# File lib/easy_geometry/d2/vector.rb, line 9
def initialize(x, y)
  @x = x; @y = y

  validate!
  converting_to_rational!
end

Public Instance Methods

-(other) click to toggle source

Subtract two vectors.

# File lib/easy_geometry/d2/vector.rb, line 23
def -(other)
  raise TypeError, "Subtract between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  Vector.new(self.x - other.x, self.y - other.y)
end
==(other) click to toggle source

Compare self and other Vector.

# File lib/easy_geometry/d2/vector.rb, line 17
def ==(other)
  return false unless other.is_a?(Vector)
  (x - other.x).abs < EQUITY_TOLERANCE && (y - other.y).abs < EQUITY_TOLERANCE
end
cross_product(other) click to toggle source

It is positive if other vector should be turned counter-clockwise in order to superpose them. It is negative if other vector should be turned clockwise in order to superpose them. It is zero when vectors are collinear.

# File lib/easy_geometry/d2/vector.rb, line 43
def cross_product(other)
  raise TypeError, "Cross product between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  x * other.y - y * other.x
end
dot(other) click to toggle source

Dot product, also known as inner product or scalar product.

# File lib/easy_geometry/d2/vector.rb, line 49
def dot(other)
  raise TypeError, "Scalar (dot) product between Vector and #{ other.class } is not defined" unless other.is_a?(Vector)
  x * other.x + y * other.y
end
orthogonal_direction() click to toggle source

Returns a non-zero vector that is orthogonal to the line containing self and the origin.

# File lib/easy_geometry/d2/vector.rb, line 30
def orthogonal_direction
  # if a coordinate is zero, we can put a 1 there and zeros elsewhere
  return Vector.new(1, 0) if x.zero?
  return Vector.new(0, 1) if y.zero?

  # if the first two coordinates aren't zero, we can create a non-zero
  # orthogonal vector by swapping them, negating one, and padding with zeros
  Vector.new(-y, x)
end
to_point() click to toggle source

Converts the vector to a point.

# File lib/easy_geometry/d2/vector.rb, line 55
def to_point
  Point.new(x, y)
end

Private Instance Methods

converting_to_rational!() click to toggle source
# File lib/easy_geometry/d2/vector.rb, line 65
def converting_to_rational!
  @x = Rational(x.to_s) unless x.is_a?(Rational)
  @y = Rational(y.to_s) unless y.is_a?(Rational)
end
validate!() click to toggle source
# File lib/easy_geometry/d2/vector.rb, line 61
def validate!
  raise TypeError, 'Coords should be numbers' if !x.is_a?(Numeric) || !y.is_a?(Numeric)
end