Search code examples
ruby-on-railsrubyincrement

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.


Solution

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