Search code examples
rubycomparison

NoMethodError: undefined method `+' for nil:NilClass- regex confusion


Can someone help me find out why I'm getting this error?

I have an if statement as follows

if (x + ship.size) <= 10

I retrieve x from the regex expression and back expression:

(1,2) =~ /(\d+),(\d+)/
 x, y = $1, $2

and I retrieve ship.size from a similar regex expression in a class object.

From my understanding, using \d in both my regex expressions is making ship.size an integer as well as x. Thus, shouldn't + be treated as addition rather than an undefined method? Any help would be appreciated. Thank you.


Solution

  • Regular expressions operate on strings. Even with \d the match will still be a string:

    "foo123bar"[/\d+/] #=> "123"
    #                      ^---^ note the quotes, this is a string
    

    If you want an integer, you have to convert the result yourself, e.g. via to_i:

    "foo123bar"[/\d+/].to_i #=> 123
    #                           ^^^ this is an integer
    

    And if no match is found, you'll get nil:

    "fooxyzbar"[/\d+/] #=> nil
    

    Regarding your error message:

    NoMethodError: undefined method `+' for nil:NilClass

    means that the receiver of + was nil. In your code:

    if (x + ship.size) <= 10
    

    that receiver is x, so x is nil. You basically have:

    if (nil + ship.size) <= 10
    

    Double-check how you retrieve x. Something like this should work:

    "123,456" =~ /(\d+),(\d+)/
    
    x = $1.to_i #=> 123
    y = $2.to_i #=> 456