rubyintegerbytefilesize

Pretty file size in Ruby?


I'm trying to make a method that converts an integer that represents bytes to a string with a 'prettied up' format.

Here's my half-working attempt:

class Integer
  def to_filesize
    {
      'B'  => 1024,
      'KB' => 1024 * 1024,
      'MB' => 1024 * 1024 * 1024,
      'GB' => 1024 * 1024 * 1024 * 1024,
      'TB' => 1024 * 1024 * 1024 * 1024 * 1024
    }.each_pair { |e, s| return "#{s / self}#{e}" if self < s }
  end
end

What am I doing wrong?


Solution

  • How about the Filesize gem ? It seems to be able to convert from bytes (and other formats) into pretty printed values:

    example:

    Filesize.from("12502343 B").pretty      # => "11.92 MiB"
    

    http://rubygems.org/gems/filesize