Equivalent of Python zfill?

Hello all,

I need a function which takes a number (x) and outputs a string which
contains x zeroes. e.g.

foo(3) = “000”
foo(5) = “00000”

etc.

in Python this function is ‘’.zfill(5)
another possibility would be 5*‘0’

Equivalents in Ruby? I would be mainly interested in a zfill equivalent
since that is faster that join or 5* imho.

Thx
Peter

2006/5/29, Peter S. [email protected]:

in Python this function is ‘’.zfill(5)
another possibility would be 5*‘0’

Equivalents in Ruby? I would be mainly interested in a zfill equivalent
since that is faster that join or 5* imho.

“0” * 7
=> “0000000”

Kind regards

robert

Robert,

“0” * 7
=> “0000000”

Thanks, i am using this at the moment, just wanted to know if there is
something faster - in Python zfill is faster than “0” * 7. I am just
asking because i am using this a lot of times, so if there is an at
least slightly faster alternative ,i should probably consider it. But if
“0”*7 is the ‘normal’ way of doing this, it’s OK with me.

Cheers,
Peter

On 5/29/06, Peter S. [email protected] wrote:

Robert,

“0” * 7
=> “0000000”

Thanks, i am using this at the moment, just wanted to know if there is
something faster - in Python zfill is faster than “0” * 7. I am just
asking because i am using this a lot of times, so if there is an at
least slightly faster alternative ,i should probably consider it. But if
“0”*7 is the ‘normal’ way of doing this, it’s OK with me.

It looks like zfill is primarily used for padding numbers, in which
case I’d use sprintf:

sprintf(“%07d”, 6) or “%07d” % 6
=> “0000006”

Not sure how well it benchmarks - probably better if it maps to the C
sprintf function. But you’re just looking for zeros without padding an
existing number? You could always pad out 0 to one less then what you
want, but I guess that would be overcomplicating things even if it was
a little faster. :slight_smile:

-Pawel

On Mon, May 29, 2006, Pawel S. wrote:

It looks like zfill is primarily used for padding numbers, in which
case I’d use sprintf:

sprintf("%07d", 6) or “%07d” % 6
=> “0000006”

You can also use String#rjust:

irb(main):001:0> ‘8’.rjust(4, ‘0’)
=> “0008”

If you just want a few string of 0 of different lengthes, you can also
use a precomputed array instead of recomputing ‘0’*4 every time

ie.

ZEROES = %w(x 0 00 000 0000)
str_with_4zeroes = ZEROES[4]

just my 2c

ZEROES = Array.new(100){|i|“0”*i}

or

ZEROES = Hash.new{|k,v|k[v]=“0”*v}

jey http://www.eachmapinject.com c,r=0,32;while r!=0;((c+=1)>31)?(c=0;r-=1; puts):print(c<r ?" ":~c&r!=0?"":" #")end