sub vs gsub in Ruby strings
While talking to Edward, a quick example in
the ruby console came up, to remind us that if we want to replace all the
occurrences in a string, we need to use gsub
, and sub
is not enough.
"foo,foo".sub(",", "")
=> "foofoo"
"foo,foo,foo".sub(",", "")
=> "foofoo,foo"
From the ruby docs on sub
Returns a copy of str with the first occurrence of pattern […]
So if we want to replace all the occurrences we should use gsub
Returns a copy of str with the all occurrences of pattern […]
"foo,foo,foo".gsub(",", "")
=> "foofoofoo"