在 ruby 中获得潜在捕获的紧凑方式

Compact way to get potential captures in ruby

我想遍历某些文本行并执行以下操作:

caps = /something(.*)to capture/.match(line).captures
do_something_with_caps(caps[0])

但我会在找不到匹配项时得到 Undefined method 'captures' for nil:NilClass。我可以将匹配分配给一个临时变量,然后在获取捕获之前测试 nil,但这对我来说似乎很冗长。有没有更紧凑的方法来做到这一点?

.match.captures替换为.scan

caps = line.scan(/something(.*)to capture/).flatten
do_something_with_caps(caps[0])

示例:

'somethingabcdto capture'.scan(/something(.*)to capture/).flatten #=> ["abcd"]
'nothing to capture here'.scan(/something(.*)to capture/).flatten #=> []
caps = $~.captures if /something(.*)to capture/.match(line)