What is the difference between gsub and sub methods for Ruby Strings
value = "abc abc"
puts value # abc abc
# Sub replaces just the first instance.
value = value.sub("abc", "---")
puts value # --- abc
# Gsub replaces all instances.
value = value.gsub("abc", "---")
puts value # --- ---
The difference is that sub
only replaces the first occurrence of the pattern specified, whereas gsub
does it for all occurrences (that is, it replaces globally).
The g
stands for global, as in replace globally (all):
In irb:
>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"