rubyguides

String#delete

str.delete([other_str]+) -> string

The delete method removes characters from a string based on the character sets you provide. Unlike gsub which works with patterns, delete operates on literal characters—making it faster for simple character removal tasks.

Key takeaways

  • String#delete removes characters, not substrings or patterns.
  • It is a good fit for quick cleanup when you know exactly which characters should disappear.
  • Use character sets to describe what to remove, or invert the set when you want to keep only a few characters.
  • Reach for gsub or a regex when the rule becomes more complex than a simple character list.

Syntax

string.delete(character_set [, other_sets]) → new_string

Parameters

ParameterTypeDefaultDescription
character_setStringRequiredThe first set of characters to remove
other_setsStringOptionalAdditional character sets to remove

Character sets work like a subtraction: delete("aeiou") removes all vowels, while delete("a-z", "0-9") removes all lowercase letters except digits.

Examples

Basic character removal

"hello world".delete("lo")
# => "he wrd"

"password123".delete("0-9")
# => "password"

When you provide more than one character set to delete, Ruby removes characters that appear in any of the supplied sets, not characters that appear in all of them. This intersection-like behavior means delete("aeiou", "b-z") will strip every character from the string because every letter belongs to at least one of those two ranges. Understanding how multiple sets combine helps you avoid accidentally removing more than you intended.

Multiple character sets

# Remove all vowels AND all consonants
"hello".delete("aeiou", "b-z")
# => "" (everything removed)

# Remove whitespace and punctuation
"Hello, World!  ".delete(" ", ",", "!")
# => "HelloWorld"

Combining character sets is also a natural way to strip punctuation and whitespace in one call. The method does not care about ordering; it simply removes every character that appears anywhere in the union of the sets you provide. This makes delete a compact alternative to chaining multiple gsub calls when the goal is pure character removal rather than pattern-based substitution.

Common Patterns

Sanitizing user input

def sanitize_username(input)
  input.delete("^a-zA-Z0-9_")
end

sanitize_username("user@name#123!")
# => "username123"

The caret (^) at the start of a character set inverts the meaning: instead of deleting the listed characters, delete keeps only those characters and removes everything else. This inverted form is especially useful for whitelist-based sanitization, where you define the allowed set once and let the method strip anything that falls outside it. For phone numbers, user input, or identifiers, the caret form often reads more naturally than enumerating every character you want to drop.

Removing unwanted characters

phone = "(555) 123-4567"
phone.delete("()- ")
# => "5551234567"

# Remove all non-digit characters
phone.delete("^0-9")
# => "5551234567"

Two calls to delete can produce the same cleaned string through different routes: one lists the characters to remove, the other lists the characters to keep. The choice between them comes down to which list is shorter and which intent reads more clearly. When the unwanted characters are a small, known set—parentheses, spaces, and dashes in a phone number—listing them directly is often the most readable choice.

Cleaning file content

content = "Line1\r\nLine2\r\nLine3"
content.delete("\r\n")
# => "Line1Line2Line3"

deleting character sets well

delete is a strong choice when you know exactly which characters should disappear and you do not need pattern matching or replacements. It is especially handy for sanitizing small inputs, stripping punctuation, or removing characters that are always unwanted in a particular field. Because it works on character sets, it stays simple and direct when the job is just “drop these characters and keep the rest.”

The method also makes it easy to express the negative case when you want to keep only a small set of characters. That can be clearer than building a larger regular expression, especially in scripts where the rule is easy to state in plain English. If the cleanup rule gets more complex, though, a pattern-based method may be easier to extend.

keeping the cleanup rule readable

delete works well when the rule can be described as a short list of characters to remove. That keeps the code easy to explain and makes it obvious what will happen to the string. It is a good fit for quick cleanup steps where the result should still look like the original text, just without a few unwanted symbols. When the transformation starts to involve more than a simple character set, a different method usually makes the intent clearer.

# When the rule outgrows a simple character set, switch to gsub
"Order #12345: shipped".gsub(/[^a-zA-Z ]/, "")
# => "Order  shipped"

Common mistakes

One common mistake is using delete when you really need replacement. delete removes the characters completely, so it is not the right tool if you need to substitute spaces, punctuation, or whole words.

Another mistake is writing a character set that is broader than intended. A range such as ^a-zA-Z0-9_ means “keep only these characters,” which is powerful, but it can easily remove more than you expected if you forget the caret.

# Quick one-liner cleanup
"user-input-123!".delete("^a-z0-9")
# => "userinput123"

Conclusion

String#delete is a focused tool for character-level cleanup. It stays fast and readable when the rule is simple, and it keeps the call site honest about what is being removed. When the transformation stops being a short character list, a pattern-based method usually gives you more room to express the intent.

See Also