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 stringsstr1 = "Edpresso"str2 = "is"str3 = "awesome"# delete some charactersstr1.delete! "es"str2.delete! "s"str3.delete! "ew"# print modified stringsputs str1puts str2puts str3
Explanation
- Line 1-4: We create the strings
str1,str2,str3. - Line 7-10: We use the
deletemethod 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.