Skip to content

Instantly share code, notes, and snippets.

@hardbap
Forked from JoshCheek/regex.rb
Last active June 26, 2018 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hardbap/aebeedcccdc46c8314dfcf33159b87e5 to your computer and use it in GitHub Desktop.
Save hardbap/aebeedcccdc46c8314dfcf33159b87e5 to your computer and use it in GitHub Desktop.
Ruby 1.9 regex, named capture groups to local variables
/(?<area_code>\d{3}) (?<local_number>\d{3}-\d{4})/ =~ "123 456-7890"
local_variables # => [:area_code, :local_number]
area_code # => "123"
local_number # => "456-7890"
regex = /(?<area_code>\d{3}) (?<local_number>\d{3}-\d{4})/
regex =~ "123 456-7890"
local_variables # => [:regex]
# also doesn't work if you switch string and regex in eval
"123 456-7890" =~ /(?<area_code>\d{3}) (?<local_number>\d{3}-\d{4})/
local_variables # => []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment