Home
Ruby
sub, gsub: Replace String
This page was last reviewed on Sep 14, 2024.
Dot Net Perls
Sub, gsub. In Ruby, string replacements can be done with the sub() or gsub methods. These are substitution methods. Gsub applies the substitution globally.
Method arguments. 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.
Example. 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.
Result The 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 value
COTE BARK
Sub versus gsub. The sub() method replaces just the first instance of a string with another. Gsub meanwhile replaces all instances.
Thus Gsub is closest to a "replace 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 value
abc 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.
Tip Regular expressions, ranges, and indexes can be used. Substring assignment is versatile and easy to do.
Substring
value = "abc abc" puts value # A substring can be changed within a string. # ... Only the first instance is replaced. value["abc"] = "def" puts value
abc abc def abc
Regexp substitution. We 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 value
bird and dog
Regexp and gsub. The gsub method too can be used with a regular expression. Unlike sub(), it will replace all the matches in the string.
Detail It is necessary to write more specific regular expressions. Here we use "\w" to prevent non-word chars from being matched.
value = "QUICKLY, SLOWLY OR HAPPILY" # Replace all word sending with "LY" with a string. value.gsub!(/\w+LY/, "REP") puts value
REP, REP OR REP
Method block. 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.
Here We uppercase all sequences of four word chars together with an uppercased, bracketed version.
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]
Special replacements. We can capture groups in sub and gsub and use a special replacement code like "\1" to insert them in the result.
Tip For multiple groups, we can use "\2" and "\3" and even further numbers. This is not demonstrated here.
Tip 2 In the 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 result
n:123 n:456 n:789
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2024 (simplify).
Home
Changes
© 2007-2024 Sam Allen.