Railsana
Railsana

Reputation: 1852

Ruby/Rails: Natural increase of string (succ)

I would like to have consecutive invoice numbers, but the succ method sucks (pun intended) in this case.

'427'.succ
> '428' (works!)

'2021-9'.succ
> '2022-0' (does not work)

'2021.9'.succ
> '2022.0' (does not work)

I couldn't find a gem for this, only a gem to sort strings naturally. If no one knows any existing solutions, I will answer this question with a self-programmed method shortly.

Upvotes: 2

Views: 190

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33491

You could use String#gsub and apply succ on the matched digit:

'427'.gsub(/\D(\d+)$|^\d+$/, &:succ)
# "428"
'2021-9'.gsub(/\D(\d+)$|^\d+$/, &:succ)
# "2021-10"
'2021-624'.gsub(/\D(\d+)$|^\d+$/, &:succ)
# "2021-625"

Upvotes: 3

Related Questions