0
0
Rubyprogramming~20 mins

Gsub with regex in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Gsub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
ARoom #, Floor #
BRoom 123, Floor 4
CRoom #23, Floor #
DRoom , Floor
Attempts:
2 left
💡 Hint
The regex /\d+/ matches one or more digits in a row.
Predict Output
intermediate
2: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
AHello World
BH*ll* W*rld
CH*ll* W*rld*
D*e**o *o*l*
Attempts:
2 left
💡 Hint
The regex matches vowels ignoring case, replacing each vowel with '*'.
Predict Output
advanced
2: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 result
Ruby
str = "a1b2c3"
result = str.gsub(/\d/) { |d| (d.to_i * 2).to_s }
puts result
Aa0b0c0
Ba1b2c3
Ca12b24c36
Da2b4c6
Attempts:
2 left
💡 Hint
The block doubles each digit found by the regex.
Predict Output
advanced
2: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
Amiddle end
Bbegin middle begin
Cbegin middle end
Dstart middle end
Attempts:
2 left
💡 Hint
The ^ anchor matches the start of the string only.
Predict Output
expert
3: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 result
Ruby
text = "abc123xyz456"
result = text.gsub(/(\D+)(\d+)/) { |match| $1.reverse + ($2.to_i + 1).to_s }
puts result
Acba124zyx457
Babc124xyz457
Ccba123zyx456
Dabc123xyz456
Attempts:
2 left
💡 Hint
The regex captures letters and digits separately; letters are reversed, digits incremented by 1.