我在Ruby 2.0中使用正则表达式中的命名捕获时遇到问题.我有一个字符串变量和一个插值的正则表达式:
str = "hello world"
re = /\w+/
/(?<greeting>#{re})/ =~ str
greeting
Run Code Online (Sandbox Code Playgroud)
它引发了以下异常:
prova.rb:4:在
<main>': undefined local variable or method问候'for main:Object(NameError)
shell返回1
但是,插值表达式在没有命名捕获的情况下工作.例如:
/(#{re})/ =~ str
$1
# => "hello"
Run Code Online (Sandbox Code Playgroud)