Class: Distance

Inherits:
Object
  • Object
show all
Defined in:
lib/distance.rb,
lib/distance/version.rb

Constant Summary collapse

MARATHON =
new(42195.0)
HALF_MARATHON =
new(21097.5)
VERSION =
'0.2.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(distance_in_meters) ⇒ Distance

Returns a new instance of Distance.



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

def initialize(distance_in_meters)
  @distance_in_meters = distance_in_meters.to_f
end

Class Method Details

.kilometers(n) ⇒ Object



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

def self.kilometers(n)
  new(n * Multiplier::KILOMETER)
end

.miles(n) ⇒ Object



22
23
24
# File 'lib/distance.rb', line 22

def self.miles(n)
  new(n * Multiplier::MILE)
end

Instance Method Details

#*(multiplier) ⇒ Object



52
53
54
55
56
57
# File 'lib/distance.rb', line 52

def *(multiplier)
  unless multiplier.is_a?(Numeric)
    raise ArgumentError, 'Can only multiply a Distance with a number'
  end
  Distance.new(to_f * multiplier)
end

#+(other) ⇒ Object



38
39
40
41
42
43
# File 'lib/distance.rb', line 38

def +(other)
  unless other.is_a?(Distance)
    raise ArgumentError, 'Can only add a Distance to a Distance'
  end
  Distance.new(to_f + other.to_f)
end

#-(other) ⇒ Object



45
46
47
48
49
50
# File 'lib/distance.rb', line 45

def -(other)
  unless other.is_a?(Distance)
    raise ArgumentError, 'Can only subtract a Distance from a Distance'
  end
  Distance.new(to_f - other.to_f)
end

#/(divisor) ⇒ Object



59
60
61
62
63
64
# File 'lib/distance.rb', line 59

def /(divisor)
  unless divisor.is_a?(Numeric)
    raise ArgumentError, 'Can only divide a Distance by a number'
  end
  Distance.new(to_f / divisor)
end

#<(other) ⇒ Object



81
82
83
84
# File 'lib/distance.rb', line 81

def <(other)
  return false unless other.is_a?(Distance)
  to_f < other.to_f
end

#<=(other) ⇒ Object



86
87
88
89
# File 'lib/distance.rb', line 86

def <=(other)
  return false unless other.is_a?(Distance)
  to_f <= other.to_f
end

#==(other) ⇒ Object



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

def ==(other)
  return false unless other.is_a?(Distance)
  to_f == other.to_f
end

#>(other) ⇒ Object



66
67
68
69
# File 'lib/distance.rb', line 66

def >(other)
  return false unless other.is_a?(Distance)
  to_f > other.to_f
end

#>=(other) ⇒ Object



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

def >=(other)
  return false unless other.is_a?(Distance)
  to_f >= other.to_f
end

#to_fObject



26
27
28
# File 'lib/distance.rb', line 26

def to_f
  distance_in_meters
end

#to_kilometersObject



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

def to_kilometers
  distance_in_meters / Multiplier::KILOMETER
end

#to_milesObject



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

def to_miles
  (distance_in_meters / Multiplier::MILE).round(2)
end