Parsing memory specs

i don’t know how many times i’ve written this…

spec = ‘2000GB’

size =
case spec
when /gb\s*$/io
spec.to_i * (2 ** 30)
when /mb\s*$/io
spec.to_i * (2 ** 20)
when /kb\s*$/io
spec.to_i * (2 ** 10)
else
spec.to_i
end

is there anything which parses memory specs anywhere in the stdlib?

should there be?

-a

···

EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
PHONE :: 303.497.6469
ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328
URL :: Solar-Terrestrial Physics Data | NCEI
TRY :: for l in ruby perl;do $l -e “print "\x3a\x2d\x29\x0a"”;done
===============================================================================

“Ara.T.Howard” Ara.T.Howard@noaa.gov schrieb im Newsbeitrag
news:Pine.LNX.4.44.0404222216280.8026-100000@fattire.ngdc.noaa.gov

i don’t know how many times i’ve written this…

spec = ‘2000GB’

size =
case spec
when /gb\s*$/io
spec.to_i * (2 ** 30)
when /mb\s*$/io
spec.to_i * (2 ** 20)
when /kb\s*$/io
spec.to_i * (2 ** 10)
else
spec.to_i
end

is there anything which parses memory specs anywhere in the stdlib?

If not, why don’t you put it into a file and store that in ~/lib/ruby?

Btw. personally I would choose a different implementation.

def parse_mem_size(spec)
m = /^(\d+) ?(?:([kmgt])b)?$/i.match( spec ) or
raise ArgumentError, “Illegal mem spec ‘#{spec}’”

m[1].to_i * case m[2].downcase[0]
when ?k; 1024
when ?m; 1048576
when ?g; 1073741824
when ?t; 1099511627776
else 1
end
end

But I’m sure there are tons of others… :slight_smile:

robert

“Robert Klemme” bob.news@gmx.net schrieb im Newsbeitrag
news:c6ad9d$9q96m$1@ID-52924.news.uni-berlin.de

“Ara.T.Howard” Ara.T.Howard@noaa.gov schrieb im Newsbeitrag
news:Pine.LNX.4.44.0404222216280.8026-100000@fattire.ngdc.noaa.gov

i don’t know how many times i’ve written this…

spec = ‘2000GB’

size =
case spec
when /gb\s*$/io
spec.to_i * (2 ** 30)
when /mb\s*$/io
spec.to_i * (2 ** 20)
when /kb\s*$/io
spec.to_i * (2 ** 10)
else
spec.to_i
end

is there anything which parses memory specs anywhere in the stdlib?

If not, why don’t you put it into a file and store that in ~/lib/ruby?

Btw. personally I would choose a different implementation.

def parse_mem_size(spec)
m = /^(\d+) ?(?:([kmgt])b)?$/i.match( spec ) or
raise ArgumentError, “Illegal mem spec ‘#{spec}’”

m[1].to_i * case m[2].downcase[0]
when ?k; 1024
when ?m; 1048576
when ?g; 1073741824
when ?t; 1099511627776
else 1
end
end

This should have read

def parse_mem_size(spec)
m = /^(\d+) ?(?:([kmgt])b)?$/i.match( spec ) or
raise ArgumentError, “Illegal mem spec ‘#{spec}’”

m[1].to_i * case m[2] && m[2].downcase[0]
when ?k; 1024
when ?m; 1048576
when ?g; 1073741824
when ?t; 1099511627776
else 1
end
end

A solution involving a hash for the factors is probably even faster.

Cheers

robert