Search code examples
ruby-on-railsruby

How to increment the number in a string while keeping the appropriate trailing/leading zeros


I'm curious as to how accounting softwares enable incrementing "invoice number" ie from INV-001 increments to INV-002. Let's dissect by only focusing on "001".

I've done some "Googling" and found the use of "%03d":

puts "%03d" % 1
#=> "001"

That's a start, but I struggle with many variations:

str = "001"
str = "009"

At school we were taught:

# Let's assume we knew nothing about strings
001 + 1 # gives us 002. How?

# This is what really happens
#
#  001
# +  1
# ______
#  002

Using the above, if we "add" 009 + 1, we get 010 if we use the above method.

Things are much different with programming as converting "001" to integer becomes 1.

How can I create a method that knows how to add "001" plus 1 which returns "002"?

I assume a lot of things are going on with the above formula:

  1. How it knows what to add 1 to.
  2. How it knows to bring the "remainder" to the left then add ie 009 + 1 = 010
  3. For 3, how it knows to keep a zero at the end 010 and not 10

I've tried many things but are all incorrect. Basically I need to increment the strings:

# Result should be when str is incremented by 1
str = "002" + 1 #=> "003"
str = "0002" + 1 #=> "0003"
str = "009" + 1 #=> "010"
str = "0002" + 1 #=> "0010"
str = "02" + 1 #=> "03"
str = "1" + 1 #=> "2"

Converting the str to float loses the zeros and I cant seem to use any logic successfully with "%03d".


Solution

  • You can use next like so:

    ("%03d" % 1).next #=> '002'