Padding a number with zeros

RubyString

Ruby Problem Overview


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".

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

You better use string format.

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

Solution 3 - Ruby

String#rjust:

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

Solution 4 - Ruby

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

Solution 5 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrey DeinekoView Question on Stackoverflow
Solution 1 - RubywurdeView Answer on Stackoverflow
Solution 2 - RubysawaView Answer on Stackoverflow
Solution 3 - RubyAleksei MatiushkinView Answer on Stackoverflow
Solution 4 - RubyDebadattView Answer on Stackoverflow
Solution 5 - RubyCristikView Answer on Stackoverflow