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

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

谁能帮我找出为什么会出现此错误?

我有一个if语句如下

if (x + ship.size) <= 10

我从正则表达式和反向表达式中检索 x:

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

然后我从 class 对象中的类似正则表达式中检索 ship.size。

根据我的理解,在我的两个正则表达式中使用 \d 会使 ship.size 成为整数和 x。因此,不应该将 + 视为加法而不是未定义的方法吗?任何帮助,将不胜感激。谢谢。

正则表达式对字符串进行运算。即使使用 \d 匹配仍然是一个字符串:

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

如果你想要一个整数,你必须自己转换结果,例如通过 to_i:

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

如果没有找到匹配项,您将得到 nil:

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

关于您的错误信息:

NoMethodError: undefined method `+' for nil:NilClass

表示+的接收者是nil。在您的代码中:

if (x + ship.size) <= 10

接收者是 x,所以 xnil。你基本上有:

if (nil + ship.size) <= 10

仔细检查您的检索方式 x。这样的事情应该有效:

"123,456" =~ /(\d+),(\d+)/

x = .to_i #=> 123
y = .to_i #=> 456