undefined局部变量或方法`'for main:Object

时间:2021-07-09 23:52:56

Sometimes, the following causes a strange bug:

有时,以下会导致一个奇怪的错误:

> nil || 4
NameError: undefined local variable or method ` 4' for main:Object

> nil || []
NameError: undefined local variable or method ` ' for main:Object

What is the reason?

是什么原因?

1 个解决方案

#1


9  

You are accidentally typing Alt + Space on your Mac, which produces a non-breaking space. Ruby does not consider this as whitespace, but as part of a variable name. It then complains that the variable does not exist.

您不小心在Mac上键入Alt + Space,这会产生不间断的空间。 Ruby不会将此视为空格,而是将其视为变量名称的一部分。然后它抱怨变量不存在。

Some people like to remap Alt + Space to Space in order to prevent this typo.

有些人喜欢将Alt + Space重新映射到Space以防止这种错误。

I personally like to highlight invisible characters in my text editor, so I notice the typo immediately.

我个人喜欢在文本编辑器中突出显示不可见的字符,所以我立即注意到错字。

#1


9  

You are accidentally typing Alt + Space on your Mac, which produces a non-breaking space. Ruby does not consider this as whitespace, but as part of a variable name. It then complains that the variable does not exist.

您不小心在Mac上键入Alt + Space,这会产生不间断的空间。 Ruby不会将此视为空格,而是将其视为变量名称的一部分。然后它抱怨变量不存在。

Some people like to remap Alt + Space to Space in order to prevent this typo.

有些人喜欢将Alt + Space重新映射到Space以防止这种错误。

I personally like to highlight invisible characters in my text editor, so I notice the typo immediately.

我个人喜欢在文本编辑器中突出显示不可见的字符,所以我立即注意到错字。