如何根据最后一个整数增加最后一个字符串?例如。" foo" =" f001", " foo9" =" foo10"," foo99" =" foo100"," foo001" =" foo002"
答案 0 :(得分:1)
你可以做到这一点......
def increment_string(string)
old_digits = string.scan(/\d+$/).first || ''
string.sub(/\d+$/,'') + (old_digits.to_i+1).to_s.rjust(old_digits.size, '0')
end
p increment_string("beep")
=> "beep1"
p increment_string("beep5")
=> "beep6"
p increment_string("beep99")
=> "beep100"
p increment_string("beep004")
=> "beep005"