Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to replace the content of a string in Ruby

okwudili onyejiaku

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 of str.

Example

# create some strings
str1 = "Unknown"
str2 = "was"
str3 = "hectic"

# replace some contents
a = str1.replace "Edpresso"
b = str2.replace "is"
c = str3.replace "awesome"

# print results
puts a
puts b
puts c
Replace a string content with another string content in Ruby

Explanation

  • Lines 2–4: We create some string variables and give them values.

  • Lines 7–9: We use the replace method to replace the content of the string.

  • Lines 12–14: We print the new content of the string on the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring