Class: Unitwise::Unit
Overview
A Unit is essentially a collection of Unitwise::Term. Terms can be combined
through multiplication or division to create a unit. A unit does not have
a magnitude, but it does have a scale.
Instance Method Summary
collapse
Methods included from Compatible
#<=>, #compatible_with?, #composition, #composition_string, #dim, included
Constructor Details
#initialize(input) ⇒ Unit
Create a new unit. You can send an expression or a collection of terms
collection of tems.
12
13
14
15
16
17
18
19
20
|
# File 'lib/unitwise/unit.rb', line 12
def initialize(input)
if input.respond_to?(:expression)
@expression = input.expression
elsif input.respond_to?(:each)
@terms = input
else
@expression = input.to_s
end
end
|
Instance Method Details
#*(other) ⇒ Object
54
55
56
57
58
59
60
61
62
63
64
|
# File 'lib/unitwise/unit.rb', line 54
def *(other)
if other.respond_to?(:terms)
self.class.new(terms + other.terms)
elsif other.respond_to?(:atom)
self.class.new(terms << other)
elsif other.is_a?(Numeric)
self.class.new(terms.map { |t| t * other })
else
fail TypeError, "Can't multiply #{self} by #{other}."
end
end
|
#**(other) ⇒ Object
76
77
78
79
80
81
82
|
# File 'lib/unitwise/unit.rb', line 76
def **(other)
if other.is_a?(Numeric)
self.class.new(terms.map { |t| t ** other })
else
fail TypeError, "Can't raise #{self} to #{other}."
end
end
|
#/(other) ⇒ Object
66
67
68
69
70
71
72
73
74
|
# File 'lib/unitwise/unit.rb', line 66
def /(other)
if other.respond_to?(:terms)
self.class.new(terms + other.terms.map { |t| t ** -1 })
elsif other.respond_to?(:atom)
self.class.new(terms << other ** -1)
else
fail TypeError, "Can't divide #{self} by #{other}."
end
end
|
#atoms ⇒ Object
30
31
32
|
# File 'lib/unitwise/unit.rb', line 30
def atoms
terms.map(&:atom)
end
|
#depth ⇒ Object
42
43
44
|
# File 'lib/unitwise/unit.rb', line 42
def depth
terms.map(&:depth).max + 1
end
|
#expression ⇒ Object
22
23
24
|
# File 'lib/unitwise/unit.rb', line 22
def expression
@expression ||= (Expression.compose(@terms) if @terms)
end
|
#functional(x = scalar, forward = true) ⇒ Object
38
39
40
|
# File 'lib/unitwise/unit.rb', line 38
def functional(x = scalar, forward = true)
terms.first.functional(x, forward)
end
|
#root_terms ⇒ Object
46
47
48
|
# File 'lib/unitwise/unit.rb', line 46
def root_terms
terms.flat_map(&:root_terms)
end
|
#scalar ⇒ Object
50
51
52
|
# File 'lib/unitwise/unit.rb', line 50
def scalar
terms.map(&:scalar).reduce(&:*)
end
|
#special? ⇒ Boolean
34
35
36
|
# File 'lib/unitwise/unit.rb', line 34
def special?
terms.count == 1 && terms.all?(&:special?)
end
|
#terms ⇒ Object
26
27
28
|
# File 'lib/unitwise/unit.rb', line 26
def terms
@terms ||= (Expression.decompose(@expression) if @expression)
end
|
#to_s ⇒ Object
84
85
86
|
# File 'lib/unitwise/unit.rb', line 84
def to_s
expression
end
|