0
0
Rubyprogramming~10 mins

Gsub with regex in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to replace all digits with '#' in the string.

Ruby
text = "Phone: 123-456-7890"
result = text.gsub([1], '#')
puts result
Drag options to blanks, or click blank then click option'
A"\d"
B/\d/
C/d/
D"d"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a regex pattern.
Using incorrect regex syntax like /d/ which matches letter 'd'.
2fill in blank
medium

Complete the code to replace all vowels with '*'.

Ruby
sentence = "Hello World"
new_sentence = sentence.gsub([1], '*')
puts new_sentence
Drag options to blanks, or click blank then click option'
A/[AEIOU]/
B"[aeiou]"
C/[aeiou]/
D/aeiou/
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of regex.
Not including brackets [] to form a character set.
3fill in blank
hard

Fix the error in the code to replace all whitespace with underscores.

Ruby
text = "Ruby is fun"
fixed_text = text.gsub([1], '_')
puts fixed_text
Drag options to blanks, or click blank then click option'
A/\s+/
B"\s"
C/\s/
D"\s+"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of regex.
Not using + to match multiple spaces.
4fill in blank
hard

Fill both blanks to replace all digits with 'X' only if digit is greater than 5.

Ruby
numbers = "1234567890"
result = numbers.gsub([1]) { |digit| digit.to_i [2] 5 ? 'X' : digit }
puts result
Drag options to blanks, or click blank then click option'
A/\d/
B>
C<
D/[0-9]/
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect regex or string instead of regex.
Using wrong comparison operator.
5fill in blank
hard

Fill all three blanks to replace all words starting with 'a' or 'A' with 'word'.

Ruby
text = "An apple a day keeps the doctor away"
new_text = text.gsub([1]) { |w| w.downcase.start_with?([2]) ? [3] : w }
puts new_text
Drag options to blanks, or click blank then click option'
A/\b\w+\b/
B"a"
C"word"
D"A"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect regex that doesn't match words.
Checking for uppercase 'A' only.
Not replacing with the correct string.