Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex question wrt the sub method on String

Tags:

regex

ruby

I'm running through the Koans tutorial (which is a great way to learn) and I've encountered this statement:

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

In this statement the __ is where I'm supposed to put my expected result to make the test execute correctly. I have stared at this for a while and have pulled most of it apart but I cannot figure out what the last bit means:

{ $1[0, 1] }

The expected answer is:

"one t-three"

and I was expecting:

"t-t"
like image 390
jaydel Avatar asked Jan 07 '11 14:01

jaydel


1 Answers

{ $1[0, 1] } is a block containing the expression $1[0,1]. $1[0,1] evaluates to the first character of the string $1, which contains the contents of the first capturing group of the last matched regex.

When sub is invoked with a regex and a block, it will find the first match of the regex, invoke the block, and then replace the matched substring with the result of the block.

So "one two-three".sub(/(t\w*)/) { $1[0, 1] } searches for the pattern t\w*. This finds the substring "two". Since the whole thing is in a capturing group, this substring is stored in $1. Now the block is called and returns "two"[0,1], which is "t". So "two" is replaced by "t" and you get "one t-three".

An important thing to note is that sub, unlike gsub, only replaces the first occurrence, not ever occurrence of the pattern.

like image 86
sepp2k Avatar answered Nov 10 '22 01:11

sepp2k