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

RubyString

Ruby Problem Overview


I have been perusing the documentation for String today, and I saw the :sub method, which I'd never noticed before. I've been using :gsub and it appears that they are essentially the same. Can anyone explain the difference to me? Thanks!

Ruby Solutions


Solution 1 - Ruby

The g stands for global, as in replace globally (all):

In irb:

>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"

Solution 2 - Ruby

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).

Solution 3 - Ruby

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

Solution 4 - Ruby

sub and gsub perform replacement of the first and all matches respectively.

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)


sub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )  
##"An Introduction to R Software Course will be of 8 weeks duration"

gsub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanmtView Question on Stackoverflow
Solution 1 - RubyRay ToalView Answer on Stackoverflow
Solution 2 - RubyChris BunchView Answer on Stackoverflow
Solution 3 - RubydeepakView Answer on Stackoverflow
Solution 4 - RubyHEMANTHKUMAR GADIView Answer on Stackoverflow