From 8886de4ff84992441dbe45c26dab13365ed3bb25 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 20 Dec 2020 22:39:06 -0600 Subject: [PATCH] Add Named Regex Captures Are Assigned To Variables as a ruby til --- README.md | 3 ++- ...egex-captures-are-assigned-to-variables.md | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 ruby/named-regex-captures-are-assigned-to-variables.md diff --git a/README.md b/README.md index e82429b..456a036 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_978 TILs and counting..._ +_979 TILs and counting..._ --- @@ -808,6 +808,7 @@ _978 TILs and counting..._ - [Map With Index Over An Array](ruby/map-with-index-over-an-array.md) - [Mock Method Chain Calls With RSpec](ruby/mock-method-chain-calls-with-rspec.md) - [Mocking Requests With Partial URIs Using Regex](ruby/mocking-requests-with-partial-uris-using-regex.md) +- [Named Regex Captures Are Assigned To Variables](ruby/named-regex-captures-are-assigned-to-variables.md) - [Navigate Back In The Browser With Capybara](ruby/navigate-back-in-the-browser-with-capybara.md) - [Next And Previous Floats](ruby/next-and-previous-floats.md) - [Or Operator Precedence](ruby/or-operator-precedence.md) diff --git a/ruby/named-regex-captures-are-assigned-to-variables.md b/ruby/named-regex-captures-are-assigned-to-variables.md new file mode 100644 index 0000000..2e57563 --- /dev/null +++ b/ruby/named-regex-captures-are-assigned-to-variables.md @@ -0,0 +1,24 @@ +# Named Regex Captures Are Assigned To Variables + +Both `String` and `Regexp` include the `=~` operator as a way of checking if a +string and a regex match. + +When the `Regexp` version of +[`=~`](https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-3D~) with named +capture groups, those named captures will be auto-assigned as local variables. + +Here is a regex that includes a named capture: `(?\d+)`. The parentheses +define the capture area and the `?` specifies that whatever follows in the +capture will be named `id`. + +``` +/Tile: (?\d+)/ =~ 'Tile: 1234' +#=> 0 +id +=> "1234" +``` + +After the match operator (`=~`) runs in the first line, the local variable `id` +gets assigned to whatever it matches in the corresponding string. + +[source](https://ruby-doc.org/core-2.5.1/Regexp.html#class-Regexp-label-Capturing)