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:
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:
s
by self
rather than the other way around.s
, so divide s
by 1024.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 }
end
end
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.