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?
✗ Incorrect
sub replaces only the first occurrence, while gsub replaces all.What will
"banana".gsub("a", "o") return?✗ Incorrect
All
a characters are replaced by o, so the result is "bonono".Which method can take a block to customize replacements?
✗ Incorrect
Both
sub and gsub can accept a block for dynamic replacement.What does
"abcabc".sub(/a/, "x") return?✗ Incorrect
sub replaces only the first a, so the result is "xbcabc".If you want to replace all digits in a string with "#", which method do you use?
✗ Incorrect
gsub replaces all matches, so it is used to replace all digits.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.