gsub and sub
In this page:
gsub and sub
sub(pattern, replacement) replaces the first match of a pattern in a string, and gsub() replaces every match (global substitute). Both accept either a literal string or a regular expression as the pattern, and a block form lets you compute the replacement dynamically. Like most Ruby string methods, they return a new string unless you use the ! version (gsub!).
Note: gsub accepts a block form, like text.gsub(/\\d+/) { |n| n.to_i * 2 }, letting you compute each replacement dynamically.
Example: gsub and sub
text = "cat bat cat sat"
puts text.sub("cat", "dog")
puts text.gsub("cat", "dog")
puts text.gsub(/[aeiou]/, "*")
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: