sub and gsub string methods that use regular expressions, and their in-place variants are sub! and gsub!. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. All of these methods perform a search-and-replace operation using a Regexp pattern. sub! and gsub! modify the string on which they are called whereas the sub and gsub returns a new string, leaving the original unmodified.
Below is the example to understand it better.
Example :
# Ruby program of sub and gsub method in a string roll = "2004-959-559 # This is Roll Number" # Delete Ruby-style comments roll = roll.sub!(/#.*$/, "") puts "Roll Num : #{roll}" # Remove anything other than digits roll = roll.gsub!(/\D/, "") puts "Roll Num : #{roll}" |
Output :
Roll Num : 2004-959-559 Roll Num : 2004959559
In above example, we are using sub! and gsub!. here sub! replace first occurrence of the pattern and gsub! replaces all occurrences.
Example :
# Ruby program of sub and gsub method text = "geeks for geeks, is a computer science portal" # Change "rails" to "Rails" throughout text.gsub!("geeks", "Geeks") # Capitalize the word "Rails" throughout text.gsub!(/\bgeeks\b/, "Geeks") puts "#{text}" |
Output :
Geeks for Geeks, is a computer science portal
The gsub! method too can be used with a regular expression.
Recommended Posts:
- Ruby | Set replace() function
- Ruby | Array replace() function
- Ruby | Hash replace() method
- Polymorphism in Ruby
- Ruby | Set - method
- Ruby | Keywords
- Ruby Mixins
- Ruby | Set & method
- Ruby | BigDecimal - value
- Ruby | BigDecimal -@ value
- Ruby | Set << method
- Ruby | Set + method
- Ruby | BigDecimal < value
- Ruby | Set add() method
- Ruby Directories
- Ruby | Set < method
- Ruby | at() function
- Ruby | BigDecimal % value
- Ruby | BigDecimal <= value
- Ruby | BigDecimal >= value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

