Class: Dieses::Geometry::Point

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/dieses/geometry/point.rb

Direct Known Subclasses

Mutable

Defined Under Namespace

Classes: Mutable

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x, y) ⇒ Point

Returns a new instance of Point.



10
11
12
13
14
15
# File 'lib/dieses/geometry/point.rb', line 10

def initialize(x, y)
  @x, @y = x.to_f, y.to_f
  @hash  = Point.hash ^ to_a.hash

  freeze
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



8
9
10
# File 'lib/dieses/geometry/point.rb', line 8

def hash
  @hash
end

#xObject (readonly)

Returns the value of attribute x.



8
9
10
# File 'lib/dieses/geometry/point.rb', line 8

def x
  @x
end

#yObject (readonly)

Returns the value of attribute y.



8
9
10
# File 'lib/dieses/geometry/point.rb', line 8

def y
  @y
end

Class Method Details

.call(*args) ⇒ Object



56
57
58
# File 'lib/dieses/geometry/point.rb', line 56

def call(*args)
  new(*args)
end

.cast(point) ⇒ Object



69
70
71
# File 'lib/dieses/geometry/point.rb', line 69

def cast(point)
  Point.new(point.x, point.y)
end

.distance(starting, ending) ⇒ Object



64
65
66
67
# File 'lib/dieses/geometry/point.rb', line 64

def distance(starting, ending)
  ending ||= origin
  Math.sqrt((ending.x - starting.x)**2 + (starting.y - ending.y)**2)
end

.originObject



60
61
62
# File 'lib/dieses/geometry/point.rb', line 60

def origin
  new 0.0, 0.0
end

Instance Method Details

#<=>(other) ⇒ Object



29
30
31
32
33
# File 'lib/dieses/geometry/point.rb', line 29

def <=>(other)
  return unless other.is_a? Point

  to_a <=> other.to_a
end

#approx(precision = nil) ⇒ Object



25
26
27
# File 'lib/dieses/geometry/point.rb', line 25

def approx(precision = nil)
  self.class.new Support.approx(x, precision), Support.approx(y, precision)
end

#distance(other = nil) ⇒ Object



21
22
23
# File 'lib/dieses/geometry/point.rb', line 21

def distance(other = nil)
  self.class.distance(self, other)
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/dieses/geometry/point.rb', line 35

def eql?(other)
  return false unless other.is_a? Point

  to_a == other.to_a
end

#to_aObject



47
48
49
# File 'lib/dieses/geometry/point.rb', line 47

def to_a
  [x, y]
end

#to_hObject



51
52
53
# File 'lib/dieses/geometry/point.rb', line 51

def to_h
  { x: x, y: y }
end

#to_sObject



43
44
45
# File 'lib/dieses/geometry/point.rb', line 43

def to_s
  "P(#{x}, #{y})"
end

#translate(x: nil, y: nil) ⇒ Object



17
18
19
# File 'lib/dieses/geometry/point.rb', line 17

def translate(x: nil, y: nil)
  self.class.new(self.x + (x || 0), self.y + (y || 0))
end