Class: Unitwise::Unit

Inherits:
Object
  • Object
show all
Includes:
Compatible
Defined in:
lib/unitwise/unit.rb

Instance Method Summary collapse

Methods included from Compatible

#<=>, #compatible_with?, #composition, #composition_string, #dim, included

Constructor Details

#initialize(input) ⇒ Unit

Returns a new instance of Unit.



6
7
8
9
10
11
12
13
14
# File 'lib/unitwise/unit.rb', line 6

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



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/unitwise/unit.rb', line 48

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
    raise TypeError, "Can't multiply #{inspect} by #{other}."
  end
end

#**(number) ⇒ Object



70
71
72
# File 'lib/unitwise/unit.rb', line 70

def **(number)
  self.class.new(terms.map{ |t| t ** number })
end

#/(other) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/unitwise/unit.rb', line 60

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
    raise TypeError, "Can't divide #{inspect} by #{other}."
  end
end

#atoms ⇒ Object



24
25
26
# File 'lib/unitwise/unit.rb', line 24

def atoms
  terms.map(&:atom)
end

#depth ⇒ Object



36
37
38
# File 'lib/unitwise/unit.rb', line 36

def depth
  terms.map(&:depth).max + 1
end

#expression ⇒ Object



16
17
18
# File 'lib/unitwise/unit.rb', line 16

def expression
  @expression ||= (Expression.compose(@terms) if @terms)
end

#functional(x = scalar, forward = true) ⇒ Object



32
33
34
# File 'lib/unitwise/unit.rb', line 32

def functional(x=scalar, forward=true)
  terms.first.functional(x, forward)
end

#root_terms ⇒ Object



40
41
42
# File 'lib/unitwise/unit.rb', line 40

def root_terms
  terms.flat_map(&:root_terms)
end

#scalar ⇒ Object



44
45
46
# File 'lib/unitwise/unit.rb', line 44

def scalar
  terms.map(&:scalar).inject(&:*)
end

#special? ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/unitwise/unit.rb', line 28

def special?
  terms.count == 1 && terms.all?(&:special?)
end

#terms ⇒ Object



20
21
22
# File 'lib/unitwise/unit.rb', line 20

def terms
  @terms ||= (Expression.decompose(@expression) if @expression)
end

#to_s ⇒ Object



74
75
76
# File 'lib/unitwise/unit.rb', line 74

def to_s
  expression
end