
Issue #21346 has been updated by nobu (Nobuyoshi Nakada). matheusrich (Matheus Richard) wrote in #note-3:
You say "queries that might find this pattern". That seems to say that you haven't found it yet.
I'm not sure what you mean. I just meant that the regex can find this pattern, but I can't guarantee it will _only_ find that.
Maybe like this? ```ruby "Hell".sub(/(?<!o!)\z/, "o!") #=> "Hello!" "Hello!".sub(/(?<!o!)\z/, "o!") #=> "Hello!" "o!Hell".sub(/(?<!o!)\z/, "o!") #=> "o!Hello!" ```
What's the result for
"Hello".ensure_suffix("o!")
Is it "Helloo!", or is it "Hello!"?
As currently implemented, it returns `"Helloo!"`
You should describe the corner case in the doc, and the test preferably. ---------------------------------------- Feature #21346: Introduce `String#ensure_suffix` https://bugs.ruby-lang.org/issues/21346#change-113325 * Author: matheusrich (Matheus Richard) * Status: Open ---------------------------------------- ## Problem Ensuring a string has a specific suffix or prefix is a common operation in many applications. Bundler itself uses it: https://github.com/rubygems/rubygems/blob/d409ec8b5fc647fabe30e37e17cd1ea857... Here are [GitHub search](https://github.com/search) queries that might find this pattern in other places: 1. for Ruby: `/end(?:s)?_with\?\(['"].*['"]\) \?/ lang:ruby -is:fork` 1. for Crystal (a language very similar to Ruby): `/ends_with\?\(['"].*['"]\) \?/ lang:crystal -is:fork` ## Suggested solution I believe Ruby would benefit from having a first-class method for this purpose. I suggest the `String#ensure_suffix` and `String#ensure_prefix` methods. I think these names are intuitive enough (here are 2 examples of people using `ensure` for this purpose ([1](https://github.com/boltops-tools/ufo/blob/796104fdb89163d09a58fad42add697923...), [2](https://github.com/mumuki/mumuki-domain/blob/6194089d82b1a0c8805ecba98e006de...))). I've gone ahead and implemented `String#ensure_suffix` in a [pull request](https://github.com/ruby/ruby/pull/13366) but the suggested behavior is this: ```rb "Hell".ensure_suffix("o!") # => "Hello!" "Hello!".ensure_suffix("o!") # => "Hello!" s = "Hello!" s.ensure_suffix("!").equal?(s) # => true # returns same object if already suffixed ``` -- https://bugs.ruby-lang.org/