Sub
, gsubIn Ruby, string
replacements can be done with the sub()
or gsub methods. These are substitution methods. Gsub applies the substitution globally.
We can use strings or regular expressions as the arguments to these methods. With special codes like "\1" we can insert parts of the match into a replacement.
Let us begin with this example. We use "sub!" which replaces inline, and sub()
which returns another string
. In these calls, the first argument is replaced with the second.
string
"value" has its matching characters replaced according to sub's arguments.value = "CAT" # Replace string at with OTE. value.sub!("AT", "OTE") puts value value = "BIRD" # This version of sub does not change the string in-place. value = value.sub("IRD", "ARK") puts valueCOTE BARK
Sub
versus gsubThe sub()
method replaces just the first instance of a string
with another. Gsub meanwhile replaces all instances.
string
" method. Sub()
is conceptually a "replace first string
" method.value = "abc abc" puts value # Sub replaces just the first instance. value = value.sub("abc", "---") puts value # Gsub replaces all instances. value = value.gsub("abc", "---") puts valueabc abc --- abc --- ---
Substring
We can assign a substring within a string
. This syntax has the same effect as calling sub()
on a string
. It only replaces the first match.
Substring
assignment is versatile and easy to do.value = "abc abc" puts value # A substring can be changed within a string. # ... Only the first instance is replaced. value["abc"] = "def" puts valueabc abc def abc
Regexp
substitutionWe can specify a regular expression as the first argument to sub()
and gsub. Any regular expression metacharacters can be used here.
value = "cat and dog" # Replaced at a matching the regexp with another string. value.sub!(/c\w\w/, "bird") puts valuebird and dog
Regexp
and gsubThe gsub method too can be used with a regular expression. Unlike sub()
, it will replace all the matches in the string.
value = "QUICKLY, SLOWLY OR HAPPILY" # Replace all word sending with "LY" with a string. value.gsub!(/\w+LY/, "REP") puts valueREP, REP OR REP
The sub and gsub methods can be used with method blocks. Here we declare a variable, which is filled with the matched text. The right side returns a replacement.
value = "bird and fish" # Replace all four-letter words with an uppercase version. value.gsub!(/\w{4}/) {|word| "[" + word.upcase() + "]"} puts value[BIRD] and [FISH]
We can capture groups in sub and gsub and use a special replacement code like "\1" to insert them in the result.
string
literal we use an escaped backslash character "\\1." This is needed due to a single backslash's meaning.data = "123 456 789" # Prefix all numbers with a number code. # ... We must escape the backslash. result = data.gsub(/(\d\d\d)/, "n:\\1") puts resultn:123 n:456 n:789
Sub
and gsub are powerful substitution methods in Ruby. We replace strings according to patterns. We can target just the first match, or all global matches.