When you see undefined method '[]' for nil:NilClass , it means:
Hey! You have a nil value followed by [...] , but nil does not have this method.
In this case, your problem is that match(...) sometimes does not match the desired text, returning nil , and then you cannot query [1] this. Some direct approaches to avoid this are:
match = t.cmd('actual command').match(/Calls:\s(\d{1,})/) res = match && match[1].to_i # or res = match[1].to_i if match # or res = if (match=t.cmd('actual command').match(/Calls:\s(\d{1,})/)) match[1].to_i end # or res = (match=t.cmd('actual command').match(/Calls:\s(\d{1,})/)) && match[1].to_i
However, a simpler solution is to use the String#[] method to directly capture the regular expression:
res = t.cmd('actual command')[/Calls:\s(\d+)/,1] res = res.to_i if res
This form automatically returns nil for you if the regular expression does not work, and you do not want to call to_i on nil .
I also cleaned up your regex a bit since \d{1,} equivalent to \d+ .
source share