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, precision = 16) ⇒ Base

Returns a new instance of Base.

Raises:

  • (TypeError)


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

def initialize(value, unit, valid_units, precision = 16)
  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 = BigDecimal.new value, precision
  @unit = unit.downcase
end

Instance Attribute Details

#unitObject

Returns the value of attribute unit.



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

def unit
  @unit
end

#valueObject

Returns the value of attribute value.



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

def value
  @value
end

Instance Method Details

#+(other) ⇒ Object



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

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

#-(other) ⇒ Object



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

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

#==(other) ⇒ Object



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

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



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

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

#inspectObject



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

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

#to_cObject



36
37
38
# File 'lib/convert_unit/base.rb', line 36

def to_c
  "#{value.to_c} #{unit}"
end

#to_fObject



44
45
46
# File 'lib/convert_unit/base.rb', line 44

def to_f
  "#{value.to_f} #{unit}"
end

#to_iObject



48
49
50
# File 'lib/convert_unit/base.rb', line 48

def to_i
  "#{value.to_i} #{unit}"
end

#to_rObject



40
41
42
# File 'lib/convert_unit/base.rb', line 40

def to_r;
  "#{value.to_r} #{unit}"
end

#to_sObject



52
53
54
# File 'lib/convert_unit/base.rb', line 52

def to_s
  "#{value.to_s} #{unit}"
end