小编giu*_*eta的帖子

为什么在Ruby中捕获命名组会导致"未定义的局部变量或方法"错误?

我在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)

ruby regex exception capture

4
推荐指数
1
解决办法
833
查看次数

标签 统计

capture ×1

exception ×1

regex ×1

ruby ×1