Class: Astronoby::Distance

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/astronoby/distance.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(meters) ⇒ Distance

Returns a new instance of Distance.



33
34
35
36
# File 'lib/astronoby/distance.rb', line 33

def initialize(meters)
  @meters = meters
  freeze
end

Instance Attribute Details

#metersObject (readonly) Also known as: m

Returns the value of attribute meters.



30
31
32
# File 'lib/astronoby/distance.rb', line 30

def meters
  @meters
end

Class Method Details

.from_astronomical_units(astronomical_units) ⇒ Object Also known as: from_au



23
24
25
26
# File 'lib/astronoby/distance.rb', line 23

def from_astronomical_units(astronomical_units)
  meters = astronomical_units * Constants::ASTRONOMICAL_UNIT_IN_METERS
  from_meters(meters)
end

.from_kilometers(kilometers) ⇒ Object Also known as: from_km



17
18
19
20
# File 'lib/astronoby/distance.rb', line 17

def from_kilometers(kilometers)
  meters = kilometers * Constants::KILOMETER_IN_METERS
  from_meters(meters)
end

.from_meters(meters) ⇒ Object Also known as: from_m



12
13
14
# File 'lib/astronoby/distance.rb', line 12

def from_meters(meters)
  new(meters)
end

.zeroObject



8
9
10
# File 'lib/astronoby/distance.rb', line 8

def zero
  new(0)
end

Instance Method Details

#+(other) ⇒ Object



48
49
50
# File 'lib/astronoby/distance.rb', line 48

def +(other)
  self.class.from_meters(meters + other.meters)
end

#-(other) ⇒ Object



52
53
54
# File 'lib/astronoby/distance.rb', line 52

def -(other)
  self.class.from_meters(@meters - other.meters)
end

#-@Object



56
57
58
# File 'lib/astronoby/distance.rb', line 56

def -@
  self.class.from_meters(-@meters)
end

#<=>(other) ⇒ Object



76
77
78
79
80
# File 'lib/astronoby/distance.rb', line 76

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

  meters <=> other.meters
end

#astronomical_unitsObject Also known as: au



43
44
45
# File 'lib/astronoby/distance.rb', line 43

def astronomical_units
  @meters / Constants::ASTRONOMICAL_UNIT_IN_METERS.to_f
end

#hashObject



72
73
74
# File 'lib/astronoby/distance.rb', line 72

def hash
  [meters, self.class].hash
end

#kilometersObject Also known as: km



38
39
40
# File 'lib/astronoby/distance.rb', line 38

def kilometers
  @meters / Constants::KILOMETER_IN_METERS.to_f
end

#negative?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/astronoby/distance.rb', line 64

def negative?
  meters < 0
end

#positive?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/astronoby/distance.rb', line 60

def positive?
  meters > 0
end

#zero?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/astronoby/distance.rb', line 68

def zero?
  meters.zero?
end