Skip to content

Instantly share code, notes, and snippets.

@mbklein
Created September 28, 2011 20:54
Show Gist options
  • Save mbklein/1249232 to your computer and use it in GitHub Desktop.
Save mbklein/1249232 to your computer and use it in GitHub Desktop.
Convert number of bytes to human-readable string, reducing order of magnitude
BYTE_ORDERS = ['B','KB','MB','GB','TB','PB','EB']
class Numeric
def bytestring
order = 0
while (self > 1024 ** (order+1))
order += 1
end
"%.1f %s" % [self.to_f / (1024 ** order), BYTE_ORDERS[order]]
end
end
@mbklein
Copy link
Author

mbklein commented Sep 28, 2011

ruby-1.8.7-p352 :013 > 12345678.bytestring
=> "11.8 MB" 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment