To remove a specific substring from a string in Ruby, you can use the `gsub` method.
In this example,
str
with a value of "Hello World"
.gsub
method of the string object str
with the pattern /World/
and replacement ""
to remove the specified substring.gsub
method returns a new string with all occurrences of the specified pattern replaced.str
to the console.str = "Hello World"
str = str.gsub(/World/, "")
puts "Modified string: #{str}"
Modified string: Hello
In this example,
text
with a value of "I like apple pie"
.gsub
method of the string object text
with the pattern /apple/
and replacement ""
to remove the specified substring.gsub
method creates and returns a new string with all occurrences of the specified pattern replaced.text
to the console.text = "I like apple pie"
text = text.gsub(/apple/, "")
puts "Modified string: #{text}"
Modified string: I like pie
In this tutorial, we learned How to Remove specific Substring in Ruby language with well detailed examples.