Class: Constants::Constant

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/constants/constant.rb

Overview

Constant tracks the value, uncertainty, and unit of measurement for a measured quantity. Units are tracked via ruby-units.

Direct Known Subclasses

Libraries::Physical

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, unit = nil, uncertainty = Uncertainty::UNKNOWN) ⇒ Constant

Returns a new instance of Constant.



68
69
70
71
72
# File 'lib/constants/constant.rb', line 68

def initialize(value, unit=nil, uncertainty=Uncertainty::UNKNOWN)
  @value = value
  @unit = unit.to_s.strip.empty? ? nil : Unit.new(unit)
  @uncertainty = uncertainty
end

Instance Attribute Details

#uncertaintyObject (readonly)

The uncertainty of the measured value. May be exact or unknown, represented by Uncertainty::EXACT (0) and Uncertainty::UNKNOWN (nil) respectively.



63
64
65
# File 'lib/constants/constant.rb', line 63

def uncertainty
  @uncertainty
end

#unitObject (readonly)

The units of the measured value, may be nil for unitless constants



66
67
68
# File 'lib/constants/constant.rb', line 66

def unit
  @unit
end

#valueObject (readonly)

The measured value of the constant



58
59
60
# File 'lib/constants/constant.rb', line 58

def value
  @value
end

Class Method Details

.parse(str) ⇒ Object

Parses the common notation ‘<value>(<uncertainty>)’ into a value and an uncertainty. When no uncertainty is specified, the uncertainty is nil.

Whitespace is allowed.

Base.parse("1.0(2)").vu                    # => [1.0, 0.2]
Base.parse("1.007 825 032 1(4)").vu        # => [1.0078250321, 1/2500000000]
Base.parse("6.626 068 96").vu              # => [6.62606896, nil]


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/constants/constant.rb', line 39

def parse(str)
  str = str.to_s.gsub(/\s/, '')
  raise "cannot parse: #{str}" unless str =~ /^(-?\d+)(\.\d+)?(\(\d+\))?(e-?\d+)?(.*)$/

  value = "#{$1}#{$2}#{$4}".to_f
  unit = $5
  uncertainty = case
  when $3 == nil then nil
  else
    factor = $2 == nil ? 0 : 1 - $2.length
    factor += $4[1..-1].to_i unless $4 == nil
    $3[1..-2].to_i * 10 ** factor
  end

  block_given? ? yield(value, unit, uncertainty) : new(value, unit, uncertainty)
end

Instance Method Details

#<=>(another) ⇒ Object

Compares the value of another to the value of self.



84
85
86
# File 'lib/constants/constant.rb', line 84

def <=>(another)
  value <=> another.value
end

#==(another) ⇒ Object

For Numeric inputs, compares value to another. For all other inputs, peforms the default == comparison.



76
77
78
79
80
81
# File 'lib/constants/constant.rb', line 76

def ==(another)
  case another
  when Numeric then value == another
  else super(another)
  end
end

#to_aObject

Returns the array: [value, uncertainty]



89
90
91
# File 'lib/constants/constant.rb', line 89

def to_a
  [value, uncertainty]
end