Undefined method '[]' for nil: NilClass

I am writing a quick script to retrieve data from a device using the CLI via telnet. I could help a bit with the error that I'm not sure how to handle it.

res = nil res = t.cmd('actual command').match(/Calls:\s(\d{1,})/)[1].to_i 

In some cases, the device prints all kinds of autonomous output at high speed. In addition, during this time, the device sometimes does not return all output that does not lead to a match. Thus, I get the following error:

 in `<main>': undefined method `[]' for nil:NilClass (NoMethodError) 

I tried several different things and it seems I can not get past this problem. Thanks for any help with this.

+4
source share
2 answers

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+ .

+12
source

You need conditions to check for a null result. Try something like this:

 res = nil res = t.cmd('actual command').match(/Calls:\s(\d{1,})/)[1].to_i rescue nil 

The res variable will remain null, so you can do some checks with this information later.

+1
source

Source: https://habr.com/ru/post/1433840/


All Articles