Class: MathViz::Unit
Overview
Value objects that do the actual unit tracking.
Contains all the interesting power tracking and cancellation.
Instance Attribute Summary collapse
-
#unit ⇒ Object
readonly
The interal representation.
Class Method Summary collapse
Instance Method Summary collapse
- #*(other) ⇒ Object
- #/(other) ⇒ Object
-
#binary_operator(other) ⇒ Object
(also: #+, #-, #<, #>, #==, #max, #min, #&, #|)
Implement a simple binary operation.
- #denominator ⇒ Object
-
#initialize(h = nil) ⇒ Unit
constructor
-
With a symbol, creates a simple unit.
-
- #numerator ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(h = nil) ⇒ Unit
-
With a symbol, creates a simple unit.
-
With a hash-of-powers, it simply copies those values.
-
Otherwise, it becomes a dimensionless unit.
108 109 110 111 112 113 114 115 116 |
# 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 |
Instance Attribute Details
#unit ⇒ Object (readonly)
The interal representation. Current implementation method is hash-of-powers; e.g. => 2, :s => -1 represents m*m/s
103 104 105 |
# File 'lib/mathviz.rb', line 103 def unit @unit end |
Class Method Details
.binop(other) ⇒ Object
127 128 129 |
# File 'lib/mathviz.rb', line 127 def self.binop(other) alias_method other, :binary_operator end |
Instance Method Details
#*(other) ⇒ Object
141 142 143 144 145 146 147 |
# 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) ⇒ Object
149 150 151 152 153 154 155 |
# 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 |
#binary_operator(other) ⇒ Object Also known as: +, -, <, >, ==, max, min, &, |
Implement a simple binary operation. It verifies that the units match and returns the unit ERROR if not.
119 120 121 122 123 124 125 |
# 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 |
#denominator ⇒ Object
161 162 163 |
# File 'lib/mathviz.rb', line 161 def denominator unit.reject {|u,power| power > 0} end |
#numerator ⇒ Object
157 158 159 |
# File 'lib/mathviz.rb', line 157 def numerator unit.reject {|u,power| power < 0} end |
#to_s ⇒ Object
165 166 167 168 169 170 171 |
# 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 |