Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Created March 1, 2009 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtnabe/72176 to your computer and use it in GitHub Desktop.
Save wtnabe/72176 to your computer and use it in GitHub Desktop.
# -*- 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