2.31. Removing Specific Characters

The delete method removes characters from a string if they appear in the list of characters passed as a parameter:

s1 = "To be, or not to be"
s2 = s1.delete("b")            # "To e, or not to e"
s3 = "Veni, vidi, vici!"
s4 = s3.delete(",!")           # "Veni vidi vici"

This parameter follows the same rules as the one for the count method (see section 2.28, “Counting Characters in Strings” earlier in this chapter); that is, it understands the hyphen and the caret.

There is also a delete! method.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.