Padding a number with zeros

How do I represent a number user.id as a string with:

  • 00 padded to the left if user.id is in range 0 to 9

    # => "00#{user.id}"

  • 0 padded if user.id is in range 10 to 99

    # => "0#{user.id}"

  • nothing padded otherwise

    # => "#{user.id}"

For example, having user.id = 1, it would produce "001", having user.id = 11, it would produce "011", and having user.id = 111, it would produce "111".


puts 1.to_s.rjust(3, "0")
#=> 001
puts 10.to_s.rjust(3, "0")
#=> 010
puts 100.to_s.rjust(3, "0")
#=> 100

The above code would convert your user.id into a string, then String.rjust() method would consider its length and prefix appropriate number of zeros.


You better use string format.

"%03d" % 1    #=> "001"
"%03d" % 10   #=> "010"
"%03d" % 100  #=> "100"
"%03d" % user.id # => what you want

String#rjust:

user.id
#⇒ 5
user.id.to_s.rjust(3, '0')
#⇒ "005"

You can try with the string "'%03d' % #{user.id}"


Kernel#format, or Kernel#sprintf can also be used:

format('%03d', user.id)

# or

sprintf('%03d', user.id)

As a side note, Kernel#format or Kernel#sprintf are recommended over String#% due to the ambiguity of the % operator (for example seeing a % b in the code doesn't make it clear if this is integer modulo, or string format). Also % takes as arguments an array, which might involve allocating a new object, which might carry a (maybe insignificant, but present) performance penalty.