The Pug Automatic

Ruby's String#[/regexp/]

Written March 7, 2015. Tagged Ruby, Regular expressions.

One of my favorite Ruby methods is String#[] when given a regular expression:

"fooobar"[/o+/]  # => "ooo"
"fooobar"[/o+(.)/, 1] # => "b"

The first form returns the matched part of the string. The second form returns capture group number 1.

For one thing, it's short and sweet.

For another, it's robust. "fooobar".match(/x(.)/)[1] will raise "undefined method `[]' for nil:NilClass". "fooobar"[/x(.)/, 1] will just return nil.

It's a great choice for extracting a regexp match from a string.