Skip to content

Instantly share code, notes, and snippets.

@askl56

askl56/string.rb Secret

Created November 8, 2015 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save askl56/e5bfa38db1a1da93ac84 to your computer and use it in GitHub Desktop.
Save askl56/e5bfa38db1a1da93ac84 to your computer and use it in GitHub Desktop.
# 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.
def increment_string(input)
if input.count("0-9") > 0
input.sub(/\d+/, &:next)
else
input << "1"
end
end
@askl56
Copy link
Author

askl56 commented Nov 8, 2015

Test Passed: Value == "foo1"
Test Passed: Value == "foobar002"
Test Passed: Value == "foobar2"
Test Passed: Value == "foobar01"
Test Passed: Value == "foobar100"
Test Passed: Value == "1"
Expected: "f00bar1", instead got: "f01bar"
Expected: "f00b4r1", instead got: "f01b4r"
Test Passed: Value == "foobar001"
Test Passed: Value == "foobar1000"
Test Passed: Value == "foobar01000"
Test Passed: Value == "foobar002"
Test Passed: Value == "foobar2"
Test Passed: Value == "2"
Test Passed: Value == "010"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment