As part of my Christmas reading, I am currently devouring the fantastic Ruby Best Practices from O’Reilly, which is packed with a plethora of tricks that remind you on each page why Ruby programming is joyous and beautiful.
The book pointed out one particular trick of which I wasn’t aware. When you want to capture a regular expression match from a string, you can simply index into the string with the regular expression, and the capture number.
>> str = "First name: Jeff Last name: Shantz" => "First name: Jeff Last name: Shantz" >> first_name = str[/:\s*(\w+)[^:]+:\s*(\w+)/,1] => "Jeff" >> last_name = str[/:\s*(\w+)[^:]+:\s*(\w+)/,2] => "Shantz"