赞
踩
nameerror:
In Ruby, you don't have to declare variables, but you do have to assign something to them before they can be referred to.
在Ruby中 ,不必声明变量,但必须先给它们分配一些内容,然后才能对其进行引用。
If you're referring to a local variable that doesn't yet exist, you may see one of two errors.
如果要引用尚不存在的局部变量 ,则可能会看到两个错误之一。
-
- NameError: undefined local variable or method `a' for #
-
- NameError: undefined local variable or method `a' for main:Object
Note: There might be various identifiers in place of 'a' above.
注意:上面的“ a”可能有各种标识符。
This is an example where the code will generate the Ruby "NameError" message since the variable a hasn't yet been assigned to anything:
这是一个示例,其中代码尚未生成变量a ,因此代码将生成Ruby“ NameError”消息:
-
- puts a
Variables must be assigned before they can be used. So, using the example from above, fixing the error is as simple as doing this:
必须先分配变量,然后才能使用它们。 因此,使用上面的示例,修复错误很简单:
-
- a = 10
- puts a
-
The obvious answer is that you're referring to a variable that hasn't yet been created. This is most often due to a typo but may happen when refactoring code and renaming variables.
显而易见的答案是,您指的是尚未创建的变量。 这通常是由于输入错误造成的,但是在重构代码和重命名变量时可能会发生。
You might also see the "NameError: undefined local variable" Ruby error if you intended to enter a string. Strings are understood when they exist between quotes. If you didn't use quotes, Ruby will think you meant to reference a method or variable (that doesn't exist) and throw the error.
如果您打算输入字符串,则可能还会看到“ NameError:未定义的局部变量” Ruby错误。 字符串在引号之间时会被理解。 如果您不使用引号,Ruby会认为您打算引用一个方法或变量(不存在)并抛出错误。
So, look back over your code to see what this variable is supposed to be referring to, and fix it. You may also want to search for other instances of the same variable name in the same method - if it's wrong in one place, it may be wrong in others.
因此,请查看您的代码以查看该变量应引用的内容并进行修复。 您可能还想以相同的方法搜索相同变量名称的其他实例-如果在某个地方有错误,则在其他地方有可能是错误的。
翻译自: https://www.thoughtco.com/nameerror-undefined-local-variable-2907927
nameerror:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。