Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

ruby

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.

like image 557
Dave Wilson Avatar asked May 29 '11 17:05

Dave Wilson


1 Answers

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".

like image 182
mu is too short Avatar answered Oct 21 '22 04:10

mu is too short