All posts

How to delete characters from a string in Ruby


If you need to delete characters from a string in Ruby you can do so using the #delete method on the String object.

You can pass it any number of arguments you would like, for each argument passed to the method ruby will look for a substring or substrings that matches the arguments contents and remove them from the string, the returned value being the string minus any matched patterns passed to the delete method.

=> "I like pie".delete("e")
"I lik pi"

Be careful with this though, it can sometimes have unexpected behavior. In the event you wanted to delete the word “like” you might try this:

=> "I like pie".delete("like")
"I  p"

But since “like” contains an “i” and “e”, it method also deleted those characters from the word “pie”.

To delete a full word, I would use gsub like so:

=> "I like pie".gsub("like", "")
"I  pie"

Further reading:


I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).