Actions
Feature #21346
openIntroduce `String#ensure_suffix`
Status:
Open
Assignee:
-
Target version:
-
Description
Problem¶
Ensuring a string has a specific suffix or prefix is a common operation in many applications.
Bundler itself uses it:
Here are GitHub search queries that might find this pattern in other places:
- for Ruby:
/end(?:s)?_with\?\(['"].*['"]\) \?/ lang:ruby -is:fork
- 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, 2)).
I've gone ahead and implemented String#ensure_suffix
in a pull request but the suggested behavior is this:
"Hell".ensure_suffix("o!") # => "Hello!"
"Hello!".ensure_suffix("o!") # => "Hello!"
s = "Hello!"
s.ensure_suffix("!").equal?(s) # => true # returns same object if already suffixed
Actions
Like0
Like0