How to Use the Ruby delete Method

09/22/2021

Contents

In this article, you will learn how to use the Ruby delete method.

Using the delete method

The Ruby delete method is a String class method that allows you to remove characters from a string. This method is very useful when you need to remove specific characters from a string or remove multiple occurrences of a character.

Here is how you can use the delete method in your Ruby code:

Syntax:

string.delete("characters")

The delete method takes one or more characters as its argument and removes them from the string. The characters can be specified as a string or as individual characters separated by commas. The method returns a new string with the specified characters removed. If no characters are specified, the original string is returned.

For example:

string = "Hello, World!"
string.delete("l") #=> "Heo, Word!"
string.delete("l", "o") #=> "He, Wrld!"

In the first example, the delete method removes all occurrences of the character “l” from the string. In the second example, it removes both “l” and “o” characters.

You can also use ranges of characters or regular expressions as the argument of delete.

string = "Ruby is fun!"
string.delete("a-z") #=> "Ry is fun!"
string.delete("^a-z") #=> "ubyisfun"
string.delete(/[aeiou]/) #=> "Rby s fn!"

In the first example, the delete method removes all lowercase letters from the string. In the second example, it removes all characters that are not lowercase letters. In the third example, it removes all vowels from the string.

Note that the delete method is case-sensitive, so it will not remove uppercase letters if you specify lowercase letters in the argument.

string = "Ruby is fun!"
string.delete("a-z") #=> "Ry is fun!"
string.delete("A-Z") #=> "Ruby is fun!"

In the above example, the first delete method removes all lowercase letters, while the second delete method removes all uppercase letters.

You can also use the delete! method to modify the original string in place.

string = "Ruby is fun!"
string.delete!("a-z")
puts string #=> "Ry is fun!"

In the above example, the delete! method removes all lowercase letters from the original string.