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

后端 未结 4 759
-上瘾入骨i
-上瘾入骨i 2021-01-30 05:57

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

相关标签:
4条回答
  • 2021-01-30 06:30
    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                                # --- ---
    
    0 讨论(0)
  • 2021-01-30 06:38

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

    In irb:

    >> "hello".sub('l', '*')
    => "he*lo"
    >> "hello".gsub('l', '*')
    => "he**o"
    
    0 讨论(0)
  • 2021-01-30 06:43

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

    0 讨论(0)
  • 2021-01-30 06:49

    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"
    
    0 讨论(0)
提交回复
热议问题