Module: AUOM::Algebra

Included in:
Unit
Defined in:
lib/auom/algebra.rb

Overview

The AUOM algebra

Instance Method Summary collapse

Instance Method Details

#add(operand) ⇒ Unit Also known as: +

Return addition result

Examples:


# unitless
Unit.new(1) + Unit.new(2) # => <Unit @scalar=3>

# with unit
Unit.new(1,:meter) + Unit.new(2,:meter) # => <AUOM::Unit @scalar=3 meter>

# incompatible unit
Unit.new(1,:meter) + Unit.new(2,:euro) # raises ArgumentError!

Parameters:

  • operand (Object)

Returns:



23
24
25
26
27
28
# File 'lib/auom/algebra.rb', line 23

def add(operand)
  klass = self.class
  operand = klass.convert(operand)
  assert_same_unit(operand)
  klass.new(operand.scalar + scalar, numerators, denominators)
end

#divide(operand) ⇒ Unit Also known as: /

Return division result

Examples:


# unitless
Unit.new(2) / Unit.new(1) # => <Unit @scalar=2>

# with unit
Unit.new(2, :meter) / Unit.new(1, :meter) # => <AUOM::Unit @scalar=2>

# different units
Unit.new(2, :meter) / Unit.new(1, :euro) # => <AUOM::Unit @scalar=2 meter/euro>

Parameters:

  • operand (Object)

Returns:



108
109
110
111
112
113
114
115
116
117
# File 'lib/auom/algebra.rb', line 108

def divide(operand)
  klass = self.class
  operand = klass.convert(operand)

  self * klass.new(
    1 / operand.scalar,
    operand.denominators,
    operand.numerators
  )
end

#multiply(operand) ⇒ Unit Also known as: *

Return multiplication result

Examples:


# unitless
Unit.new(2) * Unit.new(1) # => <Unit @scalar=2>

# with unit
Unit.new(2, :meter) * Unit.new(1, :meter) # => <AUOM::Unit @scalar=2 meter^2>

# different units
Unit.new(2, :meter) * Unit.new(1, :euro) # => <AUOM::Unit @scalar=2 meter*euro>

Parameters:

  • operand (Object)

Returns:



76
77
78
79
80
81
82
83
84
85
# File 'lib/auom/algebra.rb', line 76

def multiply(operand)
  klass = self.class
  operand = klass.convert(operand)

  klass.new(
    operand.scalar * scalar,
    numerators + operand.numerators,
    denominators + operand.denominators
  )
end

#subtract(operand) ⇒ Unit Also known as: -

Return subtraction result

Examples:


# unitless
Unit.new(2) - Unit.new(1) # => <Unit @scalar=1>

# with unit
Unit.new(2,:meter) - Unit.new(1,:meter) # => <AUOM::Unit @scalar=1 meter>

# incompatible unit
Unit.new(2,:meter) - Unit.new(1,:euro) # raises ArgumentError!

Parameters:

  • operand (Object)

Returns:



51
52
53
# File 'lib/auom/algebra.rb', line 51

def subtract(operand)
  add(operand * -1)
end