Pretty file size in Ruby? Pretty file size in Ruby? ruby ruby

Pretty file size in Ruby?


If you use it with Rails - what about standard Rails number helper?

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human_size

number_to_human_size(number, options = {})

?


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


I agree with @David that it's probably best to use an existing solution, but to answer your question about what you're doing wrong:

  1. The primary error is dividing s by self rather than the other way around.
  2. You really want to divide by the previous s, so divide s by 1024.
  3. Doing integer arithmetic will give you confusing results, so convert to float.
  4. Perhaps round the answer.

So:

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 "#{(self.to_f / (s / 1024)).round(2)}#{e}" if self < s }  endend

lets you:

1.to_filesize# => "1.0B"1020.to_filesize# => "1020.0B" 1024.to_filesize# => "1.0KB" 1048576.to_filesize# => "1.0MB"

Again, I don't recommend actually doing that, but it seems worth correcting the bugs.