0
0
Rubyprogramming~15 mins

Gsub and sub for replacement in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using gsub and sub for Replacement in Ruby
📖 Scenario: Imagine you have a list of product names with inconsistent formatting. You want to clean up these names by replacing certain words or characters.
🎯 Goal: You will create a Ruby program that uses sub and gsub methods to replace parts of strings. This will help you understand how to change text in Ruby.
📋 What You'll Learn
Create a string variable with a product description
Create a variable to hold the word to replace
Use sub to replace only the first occurrence of a word
Use gsub to replace all occurrences of a word
Print the results to see the changes
💡 Why This Matters
🌍 Real World
Cleaning and formatting text data is common in many jobs, like preparing product descriptions for websites or fixing typos in documents.
💼 Career
Knowing how to replace text efficiently helps in roles like data cleaning, software development, and content management.
Progress0 / 4 steps
1
Create the product description string
Create a string variable called product_description with the value "Fresh apples, apples, and more apples".
Ruby
Need a hint?

Use double quotes to create the string exactly as shown.

2
Create the word to replace
Create a string variable called word_to_replace and set it to "apples".
Ruby
Need a hint?

Remember to use double quotes for the string.

3
Use sub and gsub for replacement
Create two new variables: first_replacement that uses sub on product_description to replace the first occurrence of word_to_replace with "oranges", and all_replacements that uses gsub to replace all occurrences of word_to_replace with "oranges".
Ruby
Need a hint?

Use sub for the first occurrence and gsub for all occurrences.

4
Print the results
Print the variables first_replacement and all_replacements each on its own line.
Ruby
Need a hint?

Use puts to print each result on a new line.