Skip to content

Instantly share code, notes, and snippets.

@billhorsman
Created April 7, 2014 07:55
Show Gist options
  • Save billhorsman/10016311 to your computer and use it in GitHub Desktop.
Save billhorsman/10016311 to your computer and use it in GitHub Desktop.
Captured Groups in Regex and Ruby
# I didn't know that this test made the captured variable available as local variables.
if /(?<x>\d+)/ =~ "foo 123 bar"
puts x
end
# => 123
@billhorsman
Copy link
Author

Ruby 2.1's Regexp class says:

When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~ operator, the captured text is also assigned to local variables with corresponding names.

That's useful!

Note, this isn't new. It's been around since at least Ruby 1.9.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment