Dumaiu
7/23/2006 12:04:00 AM
Here's what I've done. Numeric formatting for output is most natural
with printf(): 'printf("%<c><n>d", <num>)', where <n> is the number of
digits, <num> is the number to be displayed, and <c> is the fill
character. So
printf( "%04d", 100 )
yields '0100', as you're padding with zeros out to four places.
This is all well and good for display purposes, but what about for
internal use? The only solution I've found so far is to use the
stringio library, which works a bit like C++'s <strstream>, if you're
familiar with that. That is, it lets you do I/O operations on Strings.
But it can be a bit odd until you get used to it. If, as above, you
wanted to convert a number to a four-character string:
require 'stringio'
s = String.new
StringIO.new( s ).printf("%04d", 100)
Variable s will now hold '0100'. The StringIO ctor takes a reference
to an existing String, so you can't do the whole operation in one
command. Note that s now functions like an output stream, repeated
StringIO operations appending to it rather than overwriting it, and you
must manually "flush" it with an empty-string assignment if you intend
to reuse it as an output buffer.
Boy, I got to use a lot of jargon in that one.
-Jonathan