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



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

def bit   ; self ; end

#bitsObject



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

def bits  ; self ; end

#byteObject



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

def byte  ; self * 8 ; end

#bytesObject



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

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"


120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/richunits/bytes.rb', line 120

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"


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/richunits/bytes.rb', line 148

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