Sylar
Sylar

Reputation: 12092

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

Upvotes: 1

Views: 326

Answers (3)

woodardj
woodardj

Reputation: 313

This may be new since the question was originally posed, but succ / next is the easiest way to handle this.

irb(main):048> 1.succ
=> 2
irb(main):049> "002".next
=> "003"
irb(main):050> "002".succ
=> "003"
irb(main):051> "0003".next
=> "0004"
irb(main):052> "009".succ
=> "010"
irb(main):003> "999".next
=> "1000"

Upvotes: 0

Stefan
Stefan

Reputation: 114258

I'm curious as to how accounting softwares enable incrementing "invoice number" ie from INV-001 increments to INV-002.

Accounting software typically doesn't operate on the previously generated string. Instead, it just stores the invoice number (i.e. the numeric part) as an ordinary integer, e.g.:

invoice_number = 9

It then formats that number according to a small template, e.g.

format('INV-%03d', invoice_number)
#=> "INV-009"

Now, going from INV-009 to INV-010 is simply a matter of incrementing the integer and running it through the formatter:

invoice_number += 1
#=> 10

format('INV-%03d', invoice_number)
#=> "INV-010"

Upvotes: 4

Sagar Pandya
Sagar Pandya

Reputation: 9508

You can use next like so:

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

Upvotes: 3

Related Questions