0
0
Rubyprogramming~20 mins

Gsub and sub for replacement in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Gsub and Sub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Difference between sub and gsub output
What is the output of the following Ruby code?
Ruby
text = "hello hello hello"
result = text.sub("hello", "hi")
puts result
Ahi hi hi
Bhi hello hello
Chello hi hello
Dhello hello hi
Attempts:
2 left
💡 Hint
Remember, sub replaces only the first occurrence.
Predict Output
intermediate
2:00remaining
Using gsub to replace all occurrences
What will this Ruby code print?
Ruby
text = "cat bat rat"
result = text.gsub("at", "og")
puts result
Acat bat rat
Bcog bat rat
Cgor gob goc
Dcog bog rog
Attempts:
2 left
💡 Hint
Think about what gsub does to all matches.
🔧 Debug
advanced
2:00remaining
Why does this sub call not replace anything?
Consider this Ruby code:
text = "apple banana apple"
result = text.sub(/Apple/, "orange")
puts result
Why does the output remain unchanged?
ABecause the regex is case-sensitive and "Apple" does not match "apple"
BBecause sub only replaces the last occurrence
CBecause the replacement string is incorrect
DBecause sub requires a string pattern, not a regex
Attempts:
2 left
💡 Hint
Check the case of the letters in the regex and the string.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this gsub usage
Which option shows the correct way to replace all digits with "#" in the string "abc123def" using gsub?
A"abc123def".gsub(/\d/, "#")
B"abc123def".gsub(/\d/, #)
C"abc123def".gsub(/\d/, '#')
D"abc123def".gsub(/\d/, "#"
Attempts:
2 left
💡 Hint
Look carefully at the quotes and parentheses.
🚀 Application
expert
3:00remaining
Using gsub with a block for conditional replacement
What is the output of this Ruby code?
text = "a1b2c3"
result = text.gsub(/\d/) { |digit| (digit.to_i * 2).to_s }
puts result
Aa1b2c3
Ba12b24c36
Ca2b4c6
Da0b0c0
Attempts:
2 left
💡 Hint
The block doubles each digit found.