Challenge - 5 Problems
Gsub and Sub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Remember,
sub replaces only the first occurrence.✗ Incorrect
The sub method replaces only the first match of the pattern. So only the first "hello" is replaced with "hi".
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Think about what
gsub does to all matches.✗ Incorrect
The gsub method replaces all occurrences of the pattern. Here, "at" in each word is replaced with "og".
🔧 Debug
advanced2:00remaining
Why does this sub call not replace anything?
Consider this Ruby code:
text = "apple banana apple" result = text.sub(/Apple/, "orange") puts resultWhy does the output remain unchanged?
Attempts:
2 left
💡 Hint
Check the case of the letters in the regex and the string.
✗ Incorrect
The regex /Apple/ is case-sensitive and does not match lowercase "apple". So no replacement happens.
📝 Syntax
advanced2: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?
Attempts:
2 left
💡 Hint
Look carefully at the quotes and parentheses.
✗ Incorrect
Option A correctly uses double quotes for the string and replacement, and the regex is properly enclosed.
🚀 Application
expert3: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 resultAttempts:
2 left
💡 Hint
The block doubles each digit found.
✗ Incorrect
The gsub with a block replaces each digit with its double. So 1→2, 2→4, 3→6.