In Files

Parent

Files

MathViz::Unit

Value objects that do the actual unit tracking.

Contains all the interesting power tracking and cancellation.

Attributes

unit[R]

The interal representation. Current implementation method is hash-of-powers; e.g. {:m => 2, :s => -1} represents m*m/s

Public Class Methods

binop(other) click to toggle source
# File lib/mathviz.rb, line 127
def self.binop(other)
  alias_method other, :binary_operator
end
new(h = nil) click to toggle source
  • With a symbol, creates a simple unit.

  • With a hash-of-powers, it simply copies those values.

  • Otherwise, it becomes a dimensionless unit.

# File lib/mathviz.rb, line 108
def initialize(h = nil)
  @unit = Hash.new(0)
  case h
  when Hash; @unit.merge!(h); normalize!
  when Symbol; @unit[h] = 1
  end
  @unit.freeze
  freeze
end

Public Instance Methods

&(other) click to toggle source
Alias for: binary_operator
*(other) click to toggle source
# File lib/mathviz.rb, line 141
def *(other)
  x = @unit.dup
  other.unit.each do |u,power|
    x[u] += power
  end
  MathViz::Unit.new(x)
end
+(other) click to toggle source
Alias for: binary_operator
-(other) click to toggle source
Alias for: binary_operator
/(other) click to toggle source
# File lib/mathviz.rb, line 149
def /(other)
  x = @unit.dup
  other.unit.each do |u,power|
    x[u] -= power
  end
  MathViz::Unit.new(x)
end
<(other) click to toggle source
Alias for: binary_operator
==(other) click to toggle source
Alias for: binary_operator
>(other) click to toggle source
Alias for: binary_operator
binary_operator(other) click to toggle source

Implement a simple binary operation. It verifies that the units match and returns the unit ERROR if not.

# File lib/mathviz.rb, line 119
def binary_operator(other)
  if (unit != other.unit)
    #p "#{to_s} !+- #{other.to_s}"
    return MathViz::Unit.new(:ERROR)
  end
  return self
end
Also aliased as: +, -, <, >, ==, max, min, &, |
denominator() click to toggle source
# File lib/mathviz.rb, line 161
def denominator
  unit.reject {|u,power| power > 0}
end
max(other) click to toggle source
Alias for: binary_operator
min(other) click to toggle source
Alias for: binary_operator
numerator() click to toggle source
# File lib/mathviz.rb, line 157
def numerator
  unit.reject {|u,power| power < 0}
end
to_s() click to toggle source
# File lib/mathviz.rb, line 165
def to_s
  n = stream(numerator)
  d = stream(denominator)
  return '' unless (n || d)
  return "#{n||1}/#{d}" if d
  return n
end
|(other) click to toggle source
Alias for: binary_operator

[Validate]

Generated with the Darkfish Rdoc Generator 2.