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?
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 = {})
?
This is my solution:
Compared to other solutions it's simpler, more efficient, and generates a more proper output.
Format
Both
to_filesize
andto_human
have issues with big numbers.format_mb
has a weird case where for example '1 MiB' is considered '1024 KiB' which is something some people might want, but certainly not me.Performance
Also, it has the best performance.
I tested each implementation with a realistic random number generator:
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
byself
rather than the other way around.s
, so divides
by 1024.So:
lets you:
Again, I don't recommend actually doing that, but it seems worth correcting the bugs.
@Darshan Computing's solution is only partial here. Since the hash keys are not guaranteed to be ordered this approach will not work reliably. You could fix this by doing something like this inside the to_filesize method,
This is what I ended up doing for a similar method inside Float,
How about the Filesize gem ? It seems to be able to convert from bytes (and other formats) into pretty printed values:
example:
http://rubygems.org/gems/filesize
You get points for adding a method to Integer, but this seems more File specific, so I would suggest monkeying around with File, say by adding a method to File called .prettysize().
But here is an alternative solution that uses iteration, and avoids printing single bytes as float :-)