Class: Dcc::QuantityMath::Quantity

Inherits:
Object
  • Object
show all
Defined in:
lib/dcc/quantity_math/quantity.rb

Overview

A simple (value, unit, uncertainty) value object used by Dcc::QuantityMath::Real for arithmetic. Immutable.

Direct Known Subclasses

Real

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value:, unit: nil, uncertainty: nil) ⇒ Quantity

Returns a new instance of Quantity.

Parameters:

  • value (BigDecimal, Numeric)
  • unit (String, nil) (defaults to: nil)

    siunitx expression

  • uncertainty (BigDecimal, Numeric, nil) (defaults to: nil)

    1σ absolute uncertainty



15
16
17
18
19
# File 'lib/dcc/quantity_math/quantity.rb', line 15

def initialize(value:, unit: nil, uncertainty: nil)
  @value = cast_decimal(value)
  @unit = unit
  @uncertainty = uncertainty.nil? ? nil : cast_decimal(uncertainty)
end

Instance Attribute Details

#uncertaintyObject (readonly)

Returns the value of attribute uncertainty.



10
11
12
# File 'lib/dcc/quantity_math/quantity.rb', line 10

def uncertainty
  @uncertainty
end

#unitObject (readonly)

Returns the value of attribute unit.



10
11
12
# File 'lib/dcc/quantity_math/quantity.rb', line 10

def unit
  @unit
end

#valueObject (readonly)

Returns the value of attribute value.



10
11
12
# File 'lib/dcc/quantity_math/quantity.rb', line 10

def value
  @value
end

Instance Method Details

#same_unit?(other) ⇒ Boolean

Returns whether units match (or both are nil).

Returns:

  • (Boolean)

    whether units match (or both are nil).



27
28
29
# File 'lib/dcc/quantity_math/quantity.rb', line 27

def same_unit?(other)
  unit == other.unit
end

#to_sObject



31
32
33
34
35
# File 'lib/dcc/quantity_math/quantity.rb', line 31

def to_s
  u = uncertain? ? " ± #{uncertainty}" : ""
  n = unit ? " #{unit}" : ""
  "#{value}#{u}#{n}"
end

#uncertain?Boolean

Returns whether the quantity carries uncertainty info.

Returns:

  • (Boolean)

    whether the quantity carries uncertainty info.



22
23
24
# File 'lib/dcc/quantity_math/quantity.rb', line 22

def uncertain?
  !uncertainty.nil?
end