我想遍历一些文本行并执行以下操作:
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 #=> []
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句