remove a substring from a string in ruby

To remove or replace a substring from a string in Ruby, you can use the sub or gsub method.

The sub method replaces the first occurrence of a substring with a replacement string, and the gsub method replaces all occurrences of a substring with a replacement string.

main.rb
text = "hello world"
# replace first occurrence of 'world' with 'you'
text.sub("world", "you") #=> "hello you"
# replace all occurrences of 'l' with 'x'
text.gsub("l", "x") #=> "hexxo worxd"
191 chars
6 lines

In the above example, the sub method is used to replace the first occurrence of the substring "world" with "you". The resulting string is "hello you". The gsub method is used to replace all occurrences of the substring "l" with "x". The resulting string is "hexxo worxd".

gistlibby LogSnag