0
0
Rubyprogramming~5 mins

Gsub and sub for replacement in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the sub method do in Ruby?
The sub method replaces the first occurrence of a pattern in a string with a specified replacement.
Click to reveal answer
beginner
How is gsub different from sub in Ruby?
gsub replaces all occurrences of a pattern in a string, while sub replaces only the first occurrence.
Click to reveal answer
beginner
Example: What is the result of "hello world".sub("l", "x")?
It returns "hexlo world" because only the first l is replaced by x.
Click to reveal answer
beginner
Example: What is the result of "hello world".gsub("l", "x")?
It returns "hexxo worxd" because all l characters are replaced by x.
Click to reveal answer
intermediate
Can sub and gsub accept a block for dynamic replacement?
Yes, both methods can take a block to compute the replacement dynamically for each match.
Click to reveal answer
Which Ruby method replaces only the first match in a string?
Areplace
Bgsub
Csub
Dmatch
What will "banana".gsub("a", "o") return?
A"bonono"
B"banana"
C"bonana"
D"banano"
Which method can take a block to customize replacements?
Agsub only
Bboth sub and gsub
Csub only
Dneither
What does "abcabc".sub(/a/, "x") return?
A"xbcxbc"
B"xxcabc"
C"abcabc"
D"xbcabc"
If you want to replace all digits in a string with "#", which method do you use?
Agsub
Bscan
Cmatch
Dsub
Explain the difference between sub and gsub in Ruby.
Think about how many matches each method changes.
You got /3 concepts.
    Describe how you can use a block with gsub to replace matches dynamically.
    Blocks let you decide replacement based on the match.
    You got /3 concepts.