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

后端 未结 4 761
-上瘾入骨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                                # --- ---
    

提交回复
热议问题