In this article, you will learn about the difference between gsub and tr in Ruby.
The difference between gsub and tr in Ruby
In Ruby, gsub and tr are two methods used for string manipulation. While both methods can be used to replace characters in a string, they have different functionalities and use cases.
gsub stands for “global substitution” and is used to replace all occurrences of a substring in a string with a new substring. The syntax for gsub is as follows:
Here, pattern is the substring to be replaced, and replacement is the new substring that will replace the old one. gsub returns a new string with all occurrences of the old substring replaced with the new one. For example:
string = "Hello, World!" new_string = string.gsub("o", "0") puts new_string # Output: Hell0, W0rld!
In this example, gsub replaces all occurrences of “o” with “0” in the string “Hello, World!”.
tr stands for “translate” and is used to replace single characters in a string with other characters. The syntax for tr is as follows:
Here, from_str is a string of characters to be replaced, and to_str is a string of characters that will replace them. tr returns a new string with all occurrences of characters in from_str replaced with the corresponding characters in to_str. For example:
string = "Hello, World!" new_string = string.tr("aeiou", "12345") puts new_string # Output: H2ll4, W4rld!
In this example, tr replaces all vowels in the string “Hello, World!” with the numbers 1, 2, 3, 4, and 5.
In summary, gsub is used for replacing substrings with new substrings, while tr is used for replacing individual characters with other characters. Both methods can be useful for string manipulation, and the choice between them will depend on the specific requirements of the task at hand.