Created
March 1, 2009 02:13
-
-
Save wtnabe/72176 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
=begin | |
irb(main):001:0> Size.amount( '2GB' ) | |
=> 2000000000.0 | |
irb(main):002:0> Size.amount( '2GiB' ) | |
=> 2147483648.0 | |
LICENSE : two-clause BSD | |
=end | |
module Size | |
def self.amount( str ) | |
val = 0 | |
if ( str.match( /\A([0-9.]+) *([A-Z])(i)?B\z/ ) and | |
unit.include?( $2 ) ) | |
if ( $3 == 'i' ) | |
val = $1.to_f * ib_unit[$2] | |
else | |
val = $1.to_f * si_unit[$2] | |
end | |
end | |
return val | |
end | |
def self.unit | |
return %w( K M G T P ) | |
end | |
def self.ib_unit | |
u = {} | |
i = 10 | |
unit.each { |e| | |
u[e] = 2 ** i | |
i += 10 | |
} | |
return u | |
end | |
def self.si_unit | |
u = {} | |
i = 3 | |
unit.each { |e| | |
u[e] = 10 ** i | |
i += 3 | |
} | |
return u | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment