Why does capturing named groups in Ruby lead to "undefined local variable or method" errors?

I am having problems with named regular expression captures in Ruby 2.0. I have a string variable and an interpolated regular expression:

str = "hello world"
re = /\w+/
/(?<greeting>#{re})/ =~ str
greeting

This throws the following exception:

prova.rb: 4: in <main>': undefined local variable or methodgreeting 'for main: Object (NameError)
shell returned 1

However, the interpolated expression works without named captures. For instance:

/(#{re})/ =~ str
$1
# => "hello"
+2
source share
3 answers

Named records must use literals

Ruby. Regexp # = ~ :

  • , .
  • regexp, #{} .
  • , .

, . .

+4

#match; , :

> matches = "hello world".match(/(?<greeting>\w+)/)
=> #<MatchData "hello" greeting:"hello">
> matches[:greeting]
=> "hello"

#match , :

> "hello world".match(/(?<greeting>\w+)/) {|matches| matches[:greeting] }
=> "hello"
+1

, :

str = "hello world"
# => "hello world"
re = /\w+/
# => /\w+/
re2 = /(?<greeting>#{re})/
# => /(?<greeting>(?-mix:\w+))/
md = re2.match str
# => #<MatchData "hello" greeting:"hello">
md[:greeting]
# => "hello"

Interpolation is fine with named captures, just use the MatchData object most easily returned with match.

0
source

Source: https://habr.com/ru/post/1664730/


All Articles