Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between gsub and sub methods for Ruby Strings

Tags:

string

ruby

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                                # --- ---