ruby - I am not able to increment string contains integer value? -
how increment last string based on last integer ?for eg."foo" = "f001", "foo9" = "foo10", "foo99" = "foo100","foo001" = "foo002"
one way this...
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"
Comments
Post a Comment