Method: Constants::Constant.parse
- Defined in:
- lib/constants/constant.rb
.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 |