How to delete the prefix of a string in Ruby

Overview

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.

Syntax

str.delete_prefix(prefix)

Parameters

prefix: This is the specified prefix we want to delete from str.

Return value

The value returned is a string that is a copy of str but with the prefix removed.

Code example

# create strings
str1 = "welcome"
str2 = "to"
str3 = "Edpresso"
# delete prefix
a = str1.delete_prefix!("wel")
b = str2.delete_prefix("o")
c = str3.delete_prefix("Ed")
# print results
puts a
puts b
puts c

Explanation

  • In lines 2-4, the strings are created.
  • In lines 7-9, their prefix is deleted using the delete_prefix() method.
  • In lines 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.

Free Resources