<< Back to RUBY
Ruby Sub, gsub: Replace String
Use sub and gsub to replace strings. Regular expressions are used for complex replacements.Sub, gsub. String replacements can be done with the sub() or gsub methods. These are substitution methods. Gsub applies the substitution globally.
Regexp, strings. 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.
Simple 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.
Ruby program that uses sub method
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
Output
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.
Ruby program that compares sub, gsub
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
Output
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: assignRuby program that uses substring assignment
value = "abc abc"
puts value
# A substring can be changed within a string.
# ... Only the first instance is replaced.
value["abc"] = "def"
puts value
Output
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.
Ruby program that uses sub with regexp
value = "cat and dog"
# Replaced at a matching the regexp with another string.
value.sub!(/c\w\w/, "bird")
puts value
Output
bird and dog
Regexp pattern
c The lowercase letter "c".
\w A word character (letter or digit).
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.
Important: It is often necessary to write more specific regular expressions. Here we use "\w" to prevent non-word chars from being matched.
Ruby program that uses gsub with regexp
value = "quickly, slowly or happily"
# Replace all word sending with "ly" with a string.
value.gsub!(/\w+ly/, "REP")
puts value
Output
REP, REP or REP
Regexp pattern
\w+ One or more word characters.
ly The lowercase substring "ly".
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.
Ruby program that uses gsub, method block
value = "bird and fish"
# Replace all four-letter words with an uppercase version.
value.gsub!(/\w{4}/) {|word| "[" + word.upcase() + "]"}
puts value
Output
[BIRD] and [FISH]
Regexp pattern
\w{4} Four word characters.
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.
Ruby program that uses gsub, special sequences
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
Output
n:123 n:456 n:789
With sub and gsub, we have powerful substitution methods. We replace strings according to patterns. We can target just the first match, or all global matches.
Related Links:
- Ruby Convert Types: Arrays and Strings
- Ruby File Handling: File and IO Classes
- Ruby Regexp Match Method
- Ruby String Array Examples
- Ruby include: Array Contains Method
- Ruby Class Examples: Self, Super and Module
- Ruby DateTime Examples: require date
- Ruby 2D Array Examples
- Ruby Number Examples: Integer, Float, zero and eql
- Ruby Exception Examples: Begin and Rescue
- Top 65 Ruby Interview Questions (2021)
- Ruby on Rails Interview Questions (2021)
- Ruby String Examples (each char, each line)
- Ruby if Examples: elsif, else and unless
- Ruby Math Examples: floor, ceil, round and truncate
- Ruby Sub, gsub: Replace String
- Ruby Substring Examples
- Ruby Console: Puts, Print and stdin
- Ruby Remove Duplicates From Array
- Ruby Random Number Generator: rand, srand
- Ruby Recursion Example
- Ruby ROT13 Method
- Ruby Iterator: times, step Loops
- Ruby String Length, For Loop Over Chars
- Ruby Join Example (Convert Array to String)
- Ruby Format String Examples
- Ruby Copy Array Example
- Ruby Keywords
- Ruby Nil Value Examples: NoMethodError
- Learn Ruby Tutorial
- Ruby Method: Def, Arguments and Return Values
- Ruby Fibonacci Sequence Example
- Ruby Hash Examples
- Ruby While, Until and For Loop Examples
- Learn Ruby on Rails Tutorial
- Ruby Word Count: Split Method
- Ruby Sort Arrays (Use Block Syntax)
- Ruby Case Examples: Ranges, Strings and Regexp
- Ruby Array Examples
- Ruby Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf