The g
stands for global, as in replace globally (all):
In irb:
>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"
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).
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 # --- ---
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With