def as_size( s )  prefix = %W(TiB GiB MiB KiB B)  s = s.to_f  i = prefix.length - 1  while s > 512 && i > 0    s /= 1024    i -= 1  end  (%#{s > 9 ? 'd' : '.1f'} #{prefix[i]} % s).gsub /\.0/, ''endI'd like a clean and fast code to convert raw file size to human-readable format. Any hints?Update (faster format):def as_size( s )  prefix = %W(TiB GiB MiB KiB B)  s = s.to_f  i = prefix.length - 1  while s > 512 && i > 0    s /= 1024    i -= 1  end  ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + prefix[i]endUpdate (freeze the constant):PREFIX = %W(TiB GiB MiB KiB B).freezedef as_size( s )  s = s.to_f  i = PREFIX.length - 1  while s > 512 && i > 0    i -= 1    s /= 1024  end  ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + PREFIX[i]end
Printing human-readable number of bytes
ruby
It's worth looking at how Rails does this in its number_to_human_size helper. Rather than iteration it just calculates the exponent (log x / log 1024). Paring it down to the bare essentials it looks something like this:UNITS = %W(B KiB MiB GiB TiB).freezedef as_size number  if number.to_i < 1024    exponent = 0  else    max_exp  = UNITS.size - 1    exponent = ( Math.log( number ) / Math.log( 1024 ) ).to_i # convert to base    exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit    number  /= 1024 ** exponent  end  #{number} #{UNITS[ exponent ]}end