Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby zerofill a string

Formating an Integer to be filled with zeros is easy in Ruby:

sprintf( "%010d", 345 ) #=> "0000000345"

But when I try to fill a String with zeros I can't find an easy solution:

sprintf( "%010d", "12AD" ) #=> ArgumentError: invalid value for Integer(): "12AD"
sprintf( "%010s", "12AD" ) #=> "      12AD"

I would like to obtain:

sprintf( "%010s", "12AD" ) #=> "00000012AD"
like image 201
fguillen Avatar asked Sep 20 '12 00:09

fguillen


1 Answers

You can use rjust or ljust.

>> "12AD".rjust(10, '0') #=> "00000012AD" 
like image 195
oldergod Avatar answered Oct 10 '22 18:10

oldergod