当前位置:   article > 正文

nameerror:_修复Ruby“ NameError:未定义的本地变量”错误

nameerror (undefined local variable or method `ser' for main:object) did you

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.

如果要引用尚不存在的局部变量 ,则可能会看到两个错误之一。

Ruby NameError消息 ( Ruby NameError Messages )

  1. NameError: undefined local variable or method `a' for #
  1. 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”消息:

  1. puts a

如何解决错误 ( How to Fix the Error )

Variables must be assigned before they can be used. So, using the example from above, fixing the error is as simple as doing this:

必须先分配变量,然后才能使用它们。 因此,使用上面的示例,修复错误很简单:

  1. a = 10
  2. puts a

为什么会出现此错误 ( Why You're Getting This Error )

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:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/725758
推荐阅读
相关标签
  

闽ICP备14008679号