How to replace the content of a string in Ruby
Overview
The replace method is used to replace the content of a string in Ruby.
The replace method replaces the content of a string with the corresponding values in another string.
Syntax
str.replace other_str
Parameters
-
str: The string whose content we want to replace. -
other_str: The string with which we want to replace the content ofstr.
Example
# create some stringsstr1 = "Unknown"str2 = "was"str3 = "hectic"# replace some contentsa = str1.replace "Edpresso"b = str2.replace "is"c = str3.replace "awesome"# print resultsputs aputs bputs c
Explanation
-
Lines 2–4: We create some string variables and give them values.
-
Lines 7–9: We use the
replacemethod to replace the content of the string. -
Lines 12–14: We print the new content of the string on the console.