Class: Unitwise::Expression::Composer
- Inherits:
-
Object
- Object
- Unitwise::Expression::Composer
- Defined in:
- lib/unitwise/expression/composer.rb
Overview
Composer creates string expressions for arrays of terms, following UCUM’s conventions.
Instance Attribute Summary collapse
-
#mode ⇒ Object
readonly
Returns the value of attribute mode.
-
#terms ⇒ Object
readonly
Returns the value of attribute terms.
Instance Method Summary collapse
- #denominator ⇒ Object
- #expression ⇒ Object
-
#initialize(terms, mode) ⇒ Composer
constructor
A new instance of Composer.
- #numerator ⇒ Object
- #set ⇒ Object
Constructor Details
#initialize(terms, mode) ⇒ Composer
Returns a new instance of Composer.
7 8 9 10 |
# File 'lib/unitwise/expression/composer.rb', line 7 def initialize(terms, mode) @terms = terms @mode = mode || :primary_code end |
Instance Attribute Details
#mode ⇒ Object (readonly)
Returns the value of attribute mode.
6 7 8 |
# File 'lib/unitwise/expression/composer.rb', line 6 def mode @mode end |
#terms ⇒ Object (readonly)
Returns the value of attribute terms.
6 7 8 |
# File 'lib/unitwise/expression/composer.rb', line 6 def terms @terms end |
Instance Method Details
#denominator ⇒ Object
27 28 29 30 31 |
# File 'lib/unitwise/expression/composer.rb', line 27 def denominator @denominator ||= set.select{ |_, v| v < 0 }.map do |k, v| "#{ k[:f] if k[:f] != 1 }#{ k[:p] }#{ k[:a] }#{ -v if v != -1 }" end.select { |t| !t.empty? }.join('.') end |
#expression ⇒ Object
33 34 35 36 37 38 |
# File 'lib/unitwise/expression/composer.rb', line 33 def expression @expression = [] @expression << (numerator.empty? ? '1' : numerator) (@expression << denominator) unless denominator.empty? @expression.join('/') end |
#numerator ⇒ Object
21 22 23 24 25 |
# File 'lib/unitwise/expression/composer.rb', line 21 def numerator @numerator ||= set.select{ |_, v| v > 0 }.map do |k, v| "#{ k[:f] if k[:f] != 1 }#{ k[:p] }#{ k[:a] }#{ v if v != 1 }" end.select { |t| !t.empty? }.join('.') end |
#set ⇒ Object
12 13 14 15 16 17 18 19 |
# File 'lib/unitwise/expression/composer.rb', line 12 def set @set ||= terms.reduce(SignedMultiset.new) do |s, t| identifier = { :f => t.factor, :p => (t.prefix.to_s(mode) if t.prefix), :a => (t.atom.to_s(mode) if t.atom) } s.increment(identifier, t.exponent); s end end |