Pretty file size in Ruby?
If you use it with Rails - what about standard Rails number helper?
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"
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:
- The primary error is dividing
s
byself
rather than the other way around. - You really want to divide by the previous
s
, so divides
by 1024. - Doing integer arithmetic will give you confusing results, so convert to float.
- 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.