Ruby – the difference between gsub and sub methods for Ruby Strings

rubystring

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!

Best Solution

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

In irb:

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