class Anthroposi

A class container for various constants and methods to convert numbers into string with SI prefixes

Constants

BINARY_UNITS
DECIMAL_PREFIXES
KILO
LARGEST_THRESHOLD
SIGNIFICANT_DIGITS
SI_PREFIXES

Public Class Methods

new(bytes, decimal = false) click to toggle source

@param bytes [Number] @param decimal optional @raise ArgumentError if string or number less than 1 is passed in as bytes

# File lib/anthroposi.rb, line 13
def initialize(bytes, decimal = false)
  raise(ArgumentError, 'no string or fractional number') if bytes > 0 && bytes < 1
  @bytes = bytes
  @bytes.zero? and return handle_zero(decimal)
  prepare(decimal)
  @unit = compute
end

Public Instance Methods

to_s() click to toggle source

@return [String] @example

Anthroposi.new(314159).to_s #=> "314KiB"
# File lib/anthroposi.rb, line 24
def to_s
  format @mantissa > LARGEST_THRESHOLD ? '%.2e%s' : '%s%s', @mantissa, @unit
end

Private Instance Methods

compute() click to toggle source
# File lib/anthroposi.rb, line 48
def compute
  if @ordinal < BINARY_UNITS.size
    @mantissa = significant_digits(@bytes.to_f / @thousand**@ordinal, SIGNIFICANT_DIGITS)
    return @units[@ordinal]
  end
  @mantissa = significant_digits(@bytes.to_f / @thousand**SI_PREFIXES.size, SIGNIFICANT_DIGITS)
  @units[-1]
end
handle_zero(decimal) click to toggle source
# File lib/anthroposi.rb, line 42
def handle_zero(decimal)
  @mantissa = 0
  @units = decimal ? DECIMAL_PREFIXES : BINARY_UNITS
  @unit = @units[0]
end
prepare(decimal) click to toggle source
# File lib/anthroposi.rb, line 30
def prepare(decimal)
  if decimal
    @thousand = 1000
    @units = DECIMAL_PREFIXES
    @ordinal = Math.log10(@bytes).to_i / 3
  else
    @thousand = KILO
    @units = BINARY_UNITS
    @ordinal = Math.log2(@bytes).to_i / 10
  end
end