Reason #29 • January 29th, 2026

String #delete_prefix and #delete_suffix

A very common String operation is to remove a prefix or suffix from a string. In Ruby, this is made easy with the String#delete_prefix and String#delete_suffix methods:

Ruby
url = "https://loving-ruby.com/reasons/0-introduction/"

without_trailing_slash = url.delete_suffix("/")
# => "https://loving-ruby.com/reasons/0-introduction"

without_protocol = without_trailing_slash.delete_prefix("https://")
# => "loving-ruby.com/reasons/0-introduction"

# If the prefix or suffix is not present, the string is returned as is
url.delete_suffix("/not-present")
# => "https://loving-ruby.com/reasons/0-introduction/"
      
JavaScript
// Using endsWith

const url = "https://loving-ruby.com/reasons/0-introduction/";
const withoutTrailingSlash = url.endsWith("/")
  ? url.slice(0, -1)
  : url;
// => "https://loving-ruby.com/reasons/0-introduction"

const withoutProtocol = url.startsWith("https://")
  ? withoutTrailingSlash.slice("https://".length)
  : withoutTrailingSlash;
// => "loving-ruby.com/reasons/0-introduction/"

// Using regular expressions

const withoutTrailingSlashRegex = url.replace(/\/$/, "");
// => "https://loving-ruby.com/reasons/0-introduction"

const withoutProtocolRegex = url.replace(/^https:\/\//, "");
// => "loving-ruby.com/reasons/0-introduction/"
      

I love how unambiguous these methods are. You read the code, you understand the code. No need to think about indices, lengths or regular expressions. The methods are also performant since they do only the minimal amount of work needed.

History

These methods were added relatively recently in Ruby 2.5, released on Christmas 2017. Before that, one would typically use String#sub like in the regular expression JavaScript example above.