Both sub and gsub are string methods and used for replacing a substring with another. But the difference between both sub and gsub is that sub replaces only the first occurence of a string or substring with another but the gsub will replace all occurence of a string or substring with another.
gsub method is used for global replacement.
Look at the example below:
string = 'i am in love with ruby'
In this string there are multiple occurences of character 'i' but all in lowercase.
Let's replace this lowercase 'i' with uppercase 'I'.
So if you use the sub method for this replacement, you will see that this will only replace the first lowercase 'i' with uppercase 'I'.
string.sub('i', 'I')
=> "I am in love with ruby"
But if you use gsub method for this replacement, you will find that gsub will replace all occurence of lowercase 'i' with uppercase 'I'.
string.gsub('i', 'I')
=> "I am In love wIth ruby"
And this is how both sub and gsub will work.
So now depending upon your needs you can choose any of sub and gsub method.
Ruby on Rails is a very popular and most productive web application development framework. At APPSIMPACT Academy we provide best content to learn Ruby on Rails framework.