Class: HumanSize
- Inherits:
-
Object
- Object
- HumanSize
- Defined in:
- lib/human_size.rb,
lib/human_size/version.rb
Overview
——————————————————————————– # Description # ——————————————————————————– # This is the main class and the one that does all the real work and is called by # the static access class and the direct method access above. # ——————————————————————————– #
Constant Summary collapse
- VERSION =
'1.0.0'.freeze
Instance Method Summary collapse
Instance Method Details
#human_size(bytes, a_kilobyte_is_1024_bytes = true) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/human_size.rb', line 38 def human_size(bytes, a_kilobyte_is_1024_bytes = true) suffixes_table = { # Unit prefixes used for SI file sizes. 'SI' => ['B', 'KB', 'MB', 'GB', 'TB', 'Pb', 'EB', 'ZB', 'YB'], # Unit prefixes used for binary file sizes. 'BINARY' => ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'Pib', 'EiB', 'ZiB', 'YiB'] } return 'unknown' if bytes < 0 return '0.0 B' if bytes.zero? units = if a_kilobyte_is_1024_bytes suffixes_table['BINARY'] else suffixes_table['SI'] end multiple = if a_kilobyte_is_1024_bytes 1024 else 1000 end exp = (Math.log(bytes) / Math.log(multiple)).to_i exp = units.length if exp > units.length # rubocop:disable Layout/SpaceAroundOperators format('%<bytes>.1f %<unit>s', bytes: bytes.to_f / multiple ** exp, unit: units[exp]) # rubocop:enable Layout/SpaceAroundOperators end |