One reason I love writing Ruby is that it’s optimized for programmer happiness. The Ruby community values code that is super readable.
Programmers coming from other ecosystems are often shocked at much Ruby looks like pseudo-code. Between the standard library and extensions like ActiveSupport
, working with Ruby means you can write code in a natural way.
A great example of this are the String methods delete_prefix
and delete_suffix
.
Usage
You can use delete_prefix
to, as the name says, delete a substring from the beginning of a string.
"BoringRails!".delete_prefix("Boring")
#=> "Rails!"
"#programming".delete_prefix("#")
#=> "programming"
"ISBN: 9780091929787".delete_prefix("ISBN: ")
#=> "9780091929787"
"mailto:test@example.com".delete_prefix("mailto:")
#=> "test@example.com"
github_url = "https://github.com/rails/rails"
repo_name = github_url.delete_prefix("https://github.com/")
#=> "rails/rails"
Compare this method to other options like gsub
:
github_url = "https://github.com/rails/rails"
repo_name = github_url.gsub("https://github.com/", "")
#=> "rails/rails"
While gsub
is more flexible (it can take a Regex and swap multiple occurences), the code doesn’t read as naturally as delete_prefix
. And delete_prefix
is more performant!
If you want to remove characters at the end of a string, you have two main options: chomp
and delete_suffix
.
"report.csv".chomp(".csv")
#=> "report"
"report.csv".delete_suffix(".csv")
#=> "report"
"150 cm".delete_suffix("cm").to_i
#=> 150
Stylistically, chomp
has a bit more of the whimsy that you might expect from Ruby, while delete_suffix
is a nice mirroring of delete_prefix
and more explicitly named. Both have similar performance benchmarks and are faster than sub
.
Additional Resources
Ruby API Docs: String#delete_prefix
Ruby API Docs: String#delete_suffix
Ruby Bug Tracker: Feature discussion
String method benchmarks: Fast Ruby - String
Top comments (0)