Class: MetricNumber
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- MetricNumber
- Defined in:
- lib/rvc/util.rb
Constant Summary collapse
- DECIMAL_PREFIXES =
{ 'k' => 10 ** 3, 'M' => 10 ** 6, 'G' => 10 ** 9, 'T' => 10 ** 12, 'P' => 10 ** 15, }
- BINARY_PREFIXES =
{ 'Ki' => 2 ** 10, 'Mi' => 2 ** 20, 'Gi' => 2 ** 30, 'Ti' => 2 ** 40, 'Pi' => 2 ** 50, }
- CANONICAL_PREFIXES =
Instance Attribute Summary collapse
-
#binary ⇒ Object
readonly
Returns the value of attribute binary.
-
#unit ⇒ Object
readonly
Returns the value of attribute unit.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(val, unit, binary = false) ⇒ MetricNumber
constructor
A new instance of MetricNumber.
- #to_s ⇒ Object
Constructor Details
#initialize(val, unit, binary = false) ⇒ MetricNumber
Returns a new instance of MetricNumber.
365 366 367 368 369 |
# File 'lib/rvc/util.rb', line 365 def initialize val, unit, binary=false @unit = unit @binary = binary super val.to_f end |
Instance Attribute Details
#binary ⇒ Object (readonly)
Returns the value of attribute binary.
363 364 365 |
# File 'lib/rvc/util.rb', line 363 def binary @binary end |
#unit ⇒ Object (readonly)
Returns the value of attribute unit.
363 364 365 |
# File 'lib/rvc/util.rb', line 363 def unit @unit end |
Class Method Details
.parse(str) ⇒ Object
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
# File 'lib/rvc/util.rb', line 405 def self.parse str if str =~ /^([0-9,.]+)\s*([kmgtp]i?)?/i x = $1.delete(',').to_f binary = false if $2 prefix = $2.downcase binary = prefix[1..1] == 'i' prefixes = binary ? BINARY_PREFIXES : DECIMAL_PREFIXES multiple = prefixes[CANONICAL_PREFIXES[prefix]] else multiple = 1 end units = $' new x*multiple, units, binary else raise "Problem parsing SI number #{str.inspect}" end end |
Instance Method Details
#to_s ⇒ Object
371 372 373 374 375 376 377 378 379 380 381 382 383 |
# File 'lib/rvc/util.rb', line 371 def to_s limit = @binary ? 1024 : 1000 if self < limit prefix = '' multiple = 1 else prefixes = @binary ? BINARY_PREFIXES : DECIMAL_PREFIXES prefixes = prefixes.sort_by { |k,v| v } prefix, multiple = prefixes.find { |k,v| self/v < limit } prefix, multiple = prefixes.last unless prefix end ("%0.2f %s%s" % [self/multiple, prefix, @unit]).strip end |