For clarification, here's the exact question in the about_regular_expressions.rb
file that I'm having trouble with:
def test_sub_is_like_find_and_replace
assert_equal __, "one two-three".sub(/(t\w*)/) { $1[0, 1] }
end
I know what the answer is to this, but I don't understand what's happening to get that answer. I'm pretty new to Ruby and to regex, and in particular I'm confused about the code between the braces and how that's coming into play.
The code inside the braces is a block that sub
uses to replace the match:
In the block form [...] The value returned by the block will be substituted for the match on each call.
The block receives the match as an argument but the usual regex variables ($1
, $2
, ...) are also available.
In this specific case, the $1
inside the block is "two"
and the array notation extracts the first character of $1
(which is "t"
in this case). So, the block returns "t"
and sub
replaces the "two"
in the original string with just "t"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With