Class: Base

Inherits:
Object
  • Object
show all
Defined in:
lib/convert_unit/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, unit, valid_units) ⇒ Base

Returns a new instance of Base.

Raises:

  • (TypeError)


4
5
6
7
8
9
# File 'lib/convert_unit/base.rb', line 4

def initialize(value, unit, valid_units)
  raise TypeError, 'no implicit conversion of String into Integer' unless value.is_a? Numeric
  raise TypeError, 'Invalid Unit Type' unless valid_units.include?(unit.to_s.downcase)
  @value = value
  @unit = unit.downcase
end

Instance Attribute Details

#unitObject

Returns the value of attribute unit.



2
3
4
# File 'lib/convert_unit/base.rb', line 2

def unit
  @unit
end

#valueObject

Returns the value of attribute value.



2
3
4
# File 'lib/convert_unit/base.rb', line 2

def value
  @value
end

Instance Method Details

#+(other) ⇒ Object



21
22
23
24
# File 'lib/convert_unit/base.rb', line 21

def +(other)
  b_to_a = other.to(unit)
  self.class.new(value + b_to_a.value, unit)
end

#-(other) ⇒ Object



26
27
28
29
# File 'lib/convert_unit/base.rb', line 26

def -(other)
  b_to_a = other.to(unit)
  self.class.new(value - b_to_a.value, unit)
end

#==(other) ⇒ Object



11
12
13
14
15
# File 'lib/convert_unit/base.rb', line 11

def ==(other)
  a_to_b = one_unit_a_to_b(unit, other.unit) * value
  b_to_a = one_unit_a_to_b(other.unit, unit) * other.value
  a_to_b == other.value || b_to_a == value
end

#===(other) ⇒ Object



17
18
19
# File 'lib/convert_unit/base.rb', line 17

def ===(other)
  value == other.value && unit == other.unit
end

#inspectObject



31
32
33
# File 'lib/convert_unit/base.rb', line 31

def inspect
  "#{@value}#{@unit}"
end