I’m writing a quick script to extract data from a device with a CLI via telnet. I could use a little help with an error that I’m not sure how to handle.
res = nil
res = t.cmd('actual command').match(/Calls:\s(\d{1,})/)[1].to_i
In some cases, the device is printing out all kinds of autonomous output at a rapid rate. Also, during this time, the device sometimes doesn’t return all of the output which results in no match. Thus, I get the following error:
in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
I’ve tried a few different things and can’t seem to get past this issue. Thank you for any help with this.
When you see
undefined method '[]' for nil:NilClassit means:In this case, your problem is that
match(...)is sometimes failing to match the text you want, returningnil, and then you can’t ask for[1]of that. Some direct approaches to avoid this are:However, a simpler solution is to use the
String#[]method to pull out the regex capture directly:This form automatically returns
nilfor you if the regex fails, and you don’t want to callto_ionnil.I also cleaned up your regex a little, since
\d{1,}is equivalent to\d+.