Class: Reality::Measure

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/reality/measure.rb,
lib/reality/measure/unit.rb

Defined Under Namespace

Classes: Unit

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount, unit) ⇒ Measure

Returns a new instance of Measure.



7
8
9
# File 'lib/reality/measure.rb', line 7

def initialize(amount, unit)
  @amount, @unit = Rational(amount), Unit.parse(unit)
end

Instance Attribute Details

#amountObject (readonly)

Returns the value of attribute amount.



5
6
7
# File 'lib/reality/measure.rb', line 5

def amount
  @amount
end

#unitObject (readonly)

Returns the value of attribute unit.



5
6
7
# File 'lib/reality/measure.rb', line 5

def unit
  @unit
end

Instance Method Details

#*(other) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/reality/measure.rb', line 31

def *(other)
  case other
  when Numeric
    self.class.new(amount * other, unit)
  when self.class
    self.class.new(amount * other.amount, unit * other.unit)
  else
    fail ArgumentError, "Can't multiply by #{other.class}"
  end
end

#**(num) ⇒ Object



56
57
58
# File 'lib/reality/measure.rb', line 56

def **(num)
  (num-1).times.inject(self){|res| res*self}
end

#+(other) ⇒ Object



21
22
23
24
25
# File 'lib/reality/measure.rb', line 21

def +(other)
  check_compatibility!(other)

  self.class.new(amount + other.amount, unit)
end

#-(other) ⇒ Object



27
28
29
# File 'lib/reality/measure.rb', line 27

def -(other)
  self + (-other)
end

#-@Object



17
18
19
# File 'lib/reality/measure.rb', line 17

def -@
  self.class.new(-amount, unit)
end

#/(other) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/reality/measure.rb', line 42

def /(other)
  case other
  when Numeric
    self.class.new(amount / other, unit)
  when self.class
    un = unit / other.unit
    un.scalar? ?
      amount / other.amount :
      self.class.new(amount / other.amount, un)
  else
    fail ArgumentError, "Can't divide by #{other.class}"
  end
end

#<=>(other) ⇒ Object



11
12
13
14
15
# File 'lib/reality/measure.rb', line 11

def <=>(other)
  check_compatibility!(other)
  
  amount <=> other.amount
end

#inspectObject



66
67
68
# File 'lib/reality/measure.rb', line 66

def inspect
  "#<%s(%s %s)>" % [self.class, formatted_amount, unit]
end

#to_sObject



62
63
64
# File 'lib/reality/measure.rb', line 62

def to_s
  '%s%s' % [formatted_amount, unit]
end