Ruby - Replace Substrings

1. Introduction

Replacing specific substrings within a string is a common operation in text processing and manipulation. In Ruby, the gsub method provides an efficient way to replace substrings in a string. In this guide, we'll explore how to use gsub to replace substrings in Ruby.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to enter a string.

3. Ask the user for the substring they want to replace and the new substring.

4. Use the gsub method to replace the specified substring.

5. Display the modified string to the user.

3. Code Program

# Prompt the user to enter a string
puts "Enter the original string:"
original_string = gets.chomp
# Ask the user for the substring they want to replace
puts "Enter the substring you want to replace:"
old_substring = gets.chomp
# Ask the user for the new substring
puts "Enter the new substring:"
new_substring = gets.chomp
# Replace the old substring with the new substring
modified_string = original_string.gsub(old_substring, new_substring)
# Display the modified string to the user
puts "Modified string: #{modified_string}"

Output:

Enter the original string:
Hello, World!
Enter the substring you want to replace:
World
Enter the new substring:
Universe
Modified string: Hello, Universe!

Explanation:

1. gets: This method captures user input.

2. chomp: It removes the newline character from the user input.

3. gsub: Short for "global substitution". This method searches the string for a specified substring (or pattern) and replaces it with another substring. If the substring is found multiple times, all occurrences will be replaced.

Using the gsub method, we can easily replace specific substrings in a Ruby string, making it a powerful tool for string manipulation tasks.


Comments