Ruby Koans - Regex and .sub: Don't understand the reason for the answer

For clarification, we need an exact question in the file about_regular_expressions.rb , which I am having problems with:

 def test_sub_is_like_find_and_replace assert_equal __, "one two-three".sub(/(t\w*)/) { $1[0, 1] } end 

I know the answer to this question, but I do not understand what is going on to get the answer. I'm new to Ruby and regex, and in particular, I'm confused by the code between the curly braces and how this comes into play.

+7
source share
1 answer

The code inside the brackets is the block that sub uses to replace the match:

In the block form [...], the Value returned by the block will be replaced with a match on every call.

The block receives a match as an argument, but regular regex variables ( $1 , $2 , ...) are also available.

In this particular case, $1 inside the "two" block and the array notation extracts the first character of $1 (which is equal to "t" in this case). Thus, the block returns "t" and sub replaces "two" in the original string with only "t" .

+10
source

All Articles