Module: Tins::Unit
- Defined in:
- lib/tins/unit.rb
Defined Under Namespace
Classes: FormatParser, ParserError, Prefix, UnitParser
Constant Summary collapse
- PREFIX_LC =
[ '', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y', ].each_with_index.map { |n, i| Prefix.new(n.freeze, 1000, 1000 ** i, false) }.freeze
- PREFIX_UC =
[ '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', ].each_with_index.map { |n, i| Prefix.new(n.freeze, 1024, 1024 ** i, false) }.freeze
- PREFIX_F =
[ '', 'm', 'ยต', 'n', 'p', 'f', 'a', 'z', 'y', ].each_with_index.map { |n, i| Prefix.new(n.freeze, 1000, 1000 ** -i, true) }.freeze
Class Method Summary collapse
- .format(value, format: '%f %U', prefix: 1024, unit: ?b) ⇒ Object
-
.parse(string, format: '%f %U', unit: ?b, prefix: nil) ⇒ Object
Parse the string
string
if it matchesformat
with the unitunit
and the prefixes specified byprefix
. - .parse?(string, **options) ⇒ Boolean
- .prefixes(identifier) ⇒ Object
Class Method Details
.format(value, format: '%f %U', prefix: 1024, unit: ?b) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/tins/unit.rb', line 36 def format(value, format: '%f %U', prefix: 1024, unit: ?b) prefixes = prefixes(prefix) first_prefix = prefixes.first or raise ArgumentError, 'a non-empty array of prefixes is required' if value.zero? result = format.sub('%U', unit) result %= value else prefix = prefixes[ (first_prefix.fraction ? -1 : 1) * Math.log(value.abs) / Math.log(first_prefix.step) ] result = format.sub('%U', "#{prefix.name}#{unit}") result %= (value / prefix.multiplier.to_f) end end |
.parse(string, format: '%f %U', unit: ?b, prefix: nil) ⇒ Object
Parse the string string
if it matches format
with the unit unit
and the prefixes specified by prefix
.
169 170 171 172 |
# File 'lib/tins/unit.rb', line 169 def parse(string, format: '%f %U', unit: ?b, prefix: nil) prefixes = prefixes(prefix) FormatParser.new(format, UnitParser.new(string, unit, prefixes)).parse end |
.parse?(string, **options) ⇒ Boolean
174 175 176 177 178 |
# File 'lib/tins/unit.rb', line 174 def parse?(string, **) parse(string, **) rescue ParserError nil end |