The prefix of a string is either a string or a character with which the string begins. To delete the prefix of a string, we can use the delete_prefix()
method in Ruby.
When this method is called, it returns a copy of the original string but with the specified prefix deleted.
str.delete_prefix(prefix)
prefix
: This is the specified prefix we want to delete from str
.
The value returned is a string that is a copy of str
but with the prefix removed.
# create stringsstr1 = "welcome"str2 = "to"str3 = "Edpresso"# delete prefixa = str1.delete_prefix!("wel")b = str2.delete_prefix("o")c = str3.delete_prefix("Ed")# print resultsputs aputs bputs c
2
-4
, the strings are created.7
-9
, their prefix is deleted using the delete_prefix()
method.12
-14
, their results are printed.As can be seen above, the prefixes of the strings were removed except for str2
. In line 8
, o
is not a prefix of str2
. Thus, no prefix was removed for str2
.