Introduction
Use sub and gsub to change parts of text by replacing words or characters.
Use sub and gsub to change parts of text by replacing words or characters.
string.sub(pattern, replacement) string.gsub(pattern, replacement)
sub changes only the first match it finds.
gsub changes all matches in the string.
"hello world".sub("l", "x") #=> "hexlo world"
"hello world".gsub("l", "x") #=> "hexxo worxd"
"2024/06/01".gsub("/", "-") #=> "2024-06-01"
"hello hello".sub("hello", "hi") #=> "hi hello"
This program shows how sub changes only the first 'apples' to 'oranges', while gsub changes all 'apples' in the text.
text = "I love apples and apples are tasty." first_replace = text.sub("apples", "oranges") all_replace = text.gsub("apples", "oranges") puts "Original: #{text}" puts "After sub: #{first_replace}" puts "After gsub: #{all_replace}"
Both sub and gsub return a new string; they do not change the original string unless you use sub! or gsub!.
You can use strings or regular expressions as the pattern to match.
Remember that sub only replaces the first match it finds.
sub replaces only the first match in a string.
gsub replaces all matches in a string.
Use these methods to easily change parts of text in Ruby.
sub and gsub methods in Ruby?sub behaviorsub replaces only the first occurrence of the pattern in the string.gsub behaviorgsub replaces all occurrences of the pattern in the string.sub replaces only the first match, gsub replaces all matches. -> Option B"cat and cat" using sub?sub replaces only the first match, so it is the correct method here.string.sub(pattern, replacement), so "cat and cat".sub('cat', 'dog') is correct.text = "hello hello hello"
result = text.sub('hello', 'hi')
puts resultsub does heresub replaces only the first occurrence of 'hello' with 'hi'.fruit = "apple banana apple grape"
new_fruit = fruit.sub('apple', 'orange')
puts new_fruitsub, which replaces only the first match.gsub should be used instead of sub.gsub instead of sub to replace all occurrences. -> Option A"2023-04-01 and 2023-05-01", you want to replace only the month part (the two digits after the first dash) with '12' for all dates. Which Ruby code correctly does this using gsub and a regex?-(\d{2})- matches the dash, two digits, then dash.gsub to replace all matchesgsub with the pattern and replacement '-12-' replaces the month part in all dates.Pass the test and this pattern moves unknown