Module: RichUnits::Bytes::Numeric

Included in:
Numeric
Defined in:
lib/richunits/bytes.rb

Overview

Binary Multipliers for Numeric

Additional methods for Numeric class to make working with bits and bytes easier. Bits are used as the base value and these methods can be used to convert between different magnitudes.

Synopisis

1.byte               #=> 8
2.bytes              #=> 16
1.kilobit            #=> 1024
1.kilobyte           #=> 8192

Use the in_* methods to perform the inverse operations.

8192.in_kilobytes    #=> 1
1024.in_kilobits     #=> 1

Instance Method Summary collapse

Instance Method Details

#bitObject



41
# File 'lib/richunits/bytes.rb', line 41

def bit   ; self ; end

#bitsObject



42
# File 'lib/richunits/bytes.rb', line 42

def bits  ; self ; end

#byteObject



43
# File 'lib/richunits/bytes.rb', line 43

def byte  ; self * 8 ; end

#bytesObject



44
# File 'lib/richunits/bytes.rb', line 44

def bytes ; self * 8 ; end

#strfbits(fmt = '%.2f') ⇒ Object

Formated string of bits proportial to size.

1024.bits_to_s            #=> "1.00 kb"
1048576.bits_to_s         #=> "1.00 mb"
1073741824.bits_to_s      #=> "1.00 gb"
1099511627776.bits_to_s   #=> "1.00 tb"

Takes a format string to adjust output.

1024.bits_to_s('%.0f')    #=> "1 kb"


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/richunits/bytes.rb', line 81

def strfbits(fmt='%.2f')
  case
  when self < 1024
    "#{self} bits"
  when self < 1024**2
    "#{fmt % (self.to_f / 1024)} kb"
  when self < 1024**3
    "#{fmt % (self.to_f / 1024**2)} mb"
  when self < 1024**4
    "#{fmt % (self.to_f / 1024**3)} gb"
  when self < 1024**5
    "#{fmt % (self.to_f / 1024**4)} tb"
  else
    "#{self} bits"
  end
end

#strfbytes(fmt = '%.2f') ⇒ Object Also known as: octet_units

Formated string of bytes proportial to size.

1024.bytes_to_s            #=> "1.00 KB"
1048576.bytes_to_s         #=> "1.00 MB"
1073741824.bytes_to_s      #=> "1.00 GB"
1099511627776.bytes_to_s   #=> "1.00 TB"

Takes a format string to adjust output.

1024.bytes_to_s('%.0f')    #=> "1 KB"


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/richunits/bytes.rb', line 109

def strfbytes(fmt='%.2f')
  case
  when self < 1024
    "#{self} bytes"
  when self < 1024**2
    "#{fmt % (self.to_f / 1024)} KB"
  when self < 1024**3
    "#{fmt % (self.to_f / 1024**2)} MB"
  when self < 1024**4
    "#{fmt % (self.to_f / 1024**3)} GB"
  when self < 1024**5
    "#{fmt % (self.to_f / 1024**4)} TB"
  else
    "#{self} bytes"
  end
end