How to permanently delete characters from a string in Ruby

Overview

In Ruby, we can permanently delete characters from a string by using the string.delete method. It returns a new string with the specified characters removed.

Syntax

str.delete! other_string

Parameters

str: this is the string from which we want to delete some characters permanently.

other_string: this is a mandatory string that contains the specified characters we want to delete from str.

Return value

The value returned is a string that does not contain the characters specified to remove. If str is not modified by this method, nothing or nil is returned.

Code Example

# create some strings
str1 = "Edpresso"
str2 = "is"
str3 = "awesome"
# delete some characters
str1.delete! "es"
str2.delete! "s"
str3.delete! "ew"
# print modified strings
puts str1
puts str2
puts str3

Explanation

  • Line 1-4: We create the strings str1, str2, str3.
  • Line 7-10: We use the delete method and pass strings that contain the characters we want to delete.
  • Line 12-15: We print the modified strings. As we can see when we run the code, the specified characters are permanently deleted from the strings.

Free Resources