Challenge - 5 Problems
Regex Gsub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of gsub with regex replacing digits
What is the output of this Ruby code?
text = "Room 123, Floor 4" result = text.gsub(/\d+/, "#") puts result
Ruby
text = "Room 123, Floor 4" result = text.gsub(/\d+/, "#") puts result
Attempts:
2 left
💡 Hint
The regex /\d+/ matches one or more digits in a row.
✗ Incorrect
The gsub method replaces all sequences of digits (\d+) with the string '#'. So '123' and '4' are replaced separately.
❓ Predict Output
intermediate2:00remaining
Replacing vowels with '*' using gsub and regex
What will this Ruby code print?
sentence = "Hello World" output = sentence.gsub(/[aeiou]/i, '*') puts output
Ruby
sentence = "Hello World" output = sentence.gsub(/[aeiou]/i, '*') puts output
Attempts:
2 left
💡 Hint
The regex matches vowels ignoring case, replacing each vowel with '*'.
✗ Incorrect
The regex /[aeiou]/i matches vowels regardless of case. Each vowel is replaced by '*'.
❓ Predict Output
advanced2:00remaining
Using gsub with regex and block to double digits
What is the output of this Ruby code?
str = "a1b2c3"
result = str.gsub(/\d/) { |d| (d.to_i * 2).to_s }
puts resultRuby
str = "a1b2c3" result = str.gsub(/\d/) { |d| (d.to_i * 2).to_s } puts result
Attempts:
2 left
💡 Hint
The block doubles each digit found by the regex.
✗ Incorrect
The regex matches each digit. The block converts it to integer, doubles it, then converts back to string for replacement.
❓ Predict Output
advanced2:00remaining
Effect of gsub with regex and anchors
What will this Ruby code output?
text = "start middle end" new_text = text.gsub(/^start/, "begin") puts new_text
Ruby
text = "start middle end" new_text = text.gsub(/^start/, "begin") puts new_text
Attempts:
2 left
💡 Hint
The ^ anchor matches the start of the string only.
✗ Incorrect
The regex /^start/ matches 'start' only at the beginning of the string and replaces it with 'begin'.
❓ Predict Output
expert3:00remaining
Complex gsub with regex and capture groups
What is the output of this Ruby code?
text = "abc123xyz456"
result = text.gsub(/(\D+)(\d+)/) { |match| $1.reverse + ($2.to_i + 1).to_s }
puts resultRuby
text = "abc123xyz456" result = text.gsub(/(\D+)(\d+)/) { |match| $1.reverse + ($2.to_i + 1).to_s } puts result
Attempts:
2 left
💡 Hint
The regex captures letters and digits separately; letters are reversed, digits incremented by 1.
✗ Incorrect
The regex /(\D+)(\d+)/ matches groups of letters and digits. The block reverses the letters and adds 1 to the digits before joining.