0
0
Rubyprogramming~5 mins

Gsub with regex in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A"abc123"
B"abc###"
C"###123"
D"abc#23"
Which method replaces only the first match in a string?
Agsub
Breplace
Csub
Dmatch
What does the regex /\w+/ match?
AOne or more word characters (letters, digits, underscore)
BOnly digits
CWhitespace characters
DSpecial characters
How can you use a block with gsub?
ATo convert string to uppercase
BTo ignore matches
CTo delete the string
DTo specify a dynamic replacement for each match
What will "hello world".gsub(/o/, '0') output?
A"hell0 w0rld"
B"hello world"
C"hell0 world"
D"0ell0 w0rld"
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.