我想迭代一些文本行并执行以下操作:
caps = /something(.*)to capture/.match(line).captures
do_something_with_caps(caps[0])
但是,每当我没有得到匹配时,我就会得到Undefined method 'captures' for nil:NilClass
。我可以将匹配分配给临时变量,然后在获取捕获之前测试nil
,但这对我来说似乎非常冗长。有更紧凑的方法吗?
答案 0 :(得分:0)
将.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 #=> []
答案 1 :(得分:0)
caps = $~.captures if /something(.*)to capture/.match(line)