8000 Add `String#ensure_suffix` by MatheusRich · Pull Request #13366 · ruby/ruby · GitHub
[go: up one dir, main page]

Skip to content

Add String#ensure_suffix #13366

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

MatheusRich
Copy link
Contributor
@MatheusRich MatheusRich commented May 16, 2025

Returns a new string 8000 with the given suffix appended if not present, or a
duplicate of self if it already ends with suffix.

"Hell".ensure_suffix("o!")   # => "Hello!"
"Hello!".ensure_suffix("o!") # => "Hello!"

In my microbenchmarks, writing it in C seems to be faster than in Ruby, but happy to change the implementation if the team prefers that.


Discussion: https://bugs.ruby-lang.org/issues/21346

{
if (rb_str_end_with(1, &suffix, str)) return str;

return rb_str_plus(str, suffix);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've used + here because I don't know if it is possible or desirable to use string interpolation in this case.

@MatheusRich MatheusRich force-pushed the string-ensure-suffix branch from eb09c75 to e7a1f11 Compare May 18, 2025 17:50
@nobu nobu added the Feature label May 20, 2025
Returns a new string with the given suffix appended if not present, or a
duplicate of self if it already ends with suffix.

    "Hell".ensure_suffix("o!")   # => "Hello!"
    "Hello!".ensure_suffix("o!") # => "Hello!"
@MatheusRich MatheusRich force-pushed the string-ensure-suffix branch from e7a1f11 to e7b9e36 Compare June 5, 2025 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0