string incrementer

Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.

Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

Attention: If the number has leading zeros the amount of digits should be considered.

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def (input)

return "1" if input.empty?
arr = input.rpartition(/D/)
if arr[-1].empty?
arr[-1] = "1"
else
arr[-1] = arr[-1].succ
end
return arr.join
end

def (input)
input.sub(/d*$/) { |n| n.empty? ? 1 : n.succ }
end