Recall & Review
beginner
What does the
gsub method do in Ruby?The
gsub method replaces all occurrences of a pattern in a string with a specified replacement.Click to reveal answer
beginner
How do you use a regular expression with
gsub?You pass a regular expression as the first argument to
gsub, and it replaces all matches of that pattern in the string.Click to reveal answer
beginner
Example: What is the result of
"hello123".gsub(/\d/, "*")?It replaces all digits with '*', so the result is
"hello***".Click to reveal answer
intermediate
Can
gsub use a block with regex? What does it do?Yes,
gsub can take a block. For each match, the block runs and returns the replacement string.Click to reveal answer
beginner
What is the difference between
sub and gsub?sub replaces only the first match, while gsub replaces all matches in the string.Click to reveal answer
What does
"abc123".gsub(/\d/, "#") return?✗ Incorrect
All digits (\d) are replaced by '#', so '123' becomes '###'.
Which method replaces only the first match in a string?
✗ Incorrect
sub replaces only the first occurrence, gsub replaces all.What does the regex
/\w+/ match?✗ Incorrect
\w+ matches one or more word characters like letters, digits, or underscore.How can you use a block with
gsub?✗ Incorrect
The block runs for each match and returns the replacement string dynamically.
What will
"hello world".gsub(/o/, '0') output?✗ Incorrect
All 'o' characters are replaced with '0'.
Explain how to use
gsub with a regular expression to replace all vowels in a string with '*'.Think about the regex pattern for vowels and how gsub applies replacements.
You got /4 concepts.
Describe the difference between using
sub and gsub when working with regex in Ruby.Focus on how many replacements each method performs.
You got /3 concepts.