Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

vim

ruby

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: sub will replace only the first occurrence, and gsub 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, :%s/foo/bar will look through the whole file (which is what % means) and substitute one occurrence per line, but :%s/foo/bar/g 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!")

like image 967
Nathan Long Avatar asked May 25 '11 12:05

Nathan Long


People also ask

What does GSUB return?

gsub (s, pattern, repl [, n]) Returns a copy of s in which all (or the first n , if given) occurrences of the pattern have been replaced by a replacement string specified by repl , which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

What does GSUB stand for in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

Does GSUB use regex?

Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.


2 Answers

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.

like image 164
Michael Kohl Avatar answered Sep 22 '22 15:09

Michael Kohl


I think it stands for "global".

Following vim's help from :help :s to :help s_flags to :help gdefault says:

'gdefault' 'gd'         boolean (default off)
                        global
like image 25
tjm Avatar answered Sep 25 '22 15:09

tjm