CARVIEW |
Select Language
HTTP/2 200
x-amz-id-2: BersolgGAI+sVBv+WVbjxmzPFSf6frvFs04LSL3Dfpt1B/D2J8SlbYYXb9PDU8C9UJY0wZrDf7srV9YxS0TCPzUw50PXz+zpJeo3whrO7Eg=
x-amz-request-id: EY3CD2JK0FT9KX5Y
last-modified: Fri, 16 May 2025 20:11:00 GMT
etag: "e45cc6d901bc2ba6630fef2833a9eeac"
x-amz-server-side-encryption: AES256
server: AmazonS3
content-encoding: gzip
via: 1.1 varnish, 1.1 varnish
content-type: text/plain; charset=utf-8
accept-ranges: bytes
age: 0
date: Wed, 23 Jul 2025 20:04:25 GMT
x-served-by: cache-tyo11935-TYO, cache-bom-vanm7210033-BOM
x-cache: MISS, MISS
x-cache-hits: 0, 0
x-timer: S1753301065.470874,VS0,VE461
vary: Accept-Encoding
content-length: 1088
From: "matheusrich (Matheus Richard) via ruby-core"
Date: 2025-05-16T20:00:39+00:00
Subject: [ruby-core:122154] [Ruby Feature#21346] Introduce `String#ensure_suffix`
Issue #21346 has been reported by matheusrich (Matheus Richard).
----------------------------------------
Feature #21346: Introduce `String#ensure_suffix`
https://bugs.ruby-lang.org/issues/21346
* 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/d409ec8b5fc647fabe30e37e17cd1ea857634f6b/bundler/lib/bundler/uri_normalizer.rb#L17
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/796104fdb89163d09a58fad42add697923c18294/lib/ufo/cfn/stack/builder/resources/dns.rb#L76), [2](https://github.com/mumuki/mumuki-domain/blob/6194089d82b1a0c8805ecba98e006deb1694dc8e/lib/mumuki/domain/extensions/string.rb#L6))).
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/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/