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

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 )


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

如何解决错误 ( 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:

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


a = 10
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:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值