view raw
Nathan Long Nathan Long - 6 months ago 30
Ruby Question

What does the "g" stand for in Ruby's "gsub" and in Vim's substitution command?

Both Ruby and Vim use "g" with substitution commands to mean "all occurrences." What does the "g" stand for?

Specifically, in Ruby, the String class has two "sub" commands:

will replace only the first occurrence, and
will replace all occurrences. For example:

string = "One potato, two potato, three potato, four."
string.sub('potato','banana') # => "One banana, two potato, three potato, four."
string.gsub('potato','banana') # => "One banana, two banana, three banana, four."

Similarly, in Vim,
will look through the whole file (which is what
means) and substitute one occurrence per line, but
will do all occurrences on each line.

My guess would be that in both cases, "g" means "greedy," because both the Ruby commands and the Vim command accept a regular expression, but my understanding of greedy matching is "match the longest possible substring meeting these criteria," not "match as many substrings as possible." (See "Watch Out for The Greediness!")


If I remember correctly it means global, which this Wiki page seems to confirm:

The g flag means global – each occurrence in the line is changed, rather than just the first.