Ruby 模块语法错误
我在理解 Ruby 中的模块时遇到一些问题,特别是变量的存储方式。我遇到的麻烦是这样的;
module Mod
MODE = 0
def Mod.beginSearch
MODE = 2
end
end
我收到语法错误,该错误将我指向“MODE = 2”行。我的环境不会告诉我更多信息,所以我不知道是什么原因造成的。
I'm having a few issues understanding Modules in Ruby, specifically how variables are stored. The trouble I'm having is this;
module Mod
MODE = 0
def Mod.beginSearch
MODE = 2
end
end
I'm getting a syntax error, which is pointing me to the line "MODE = 2". My environment won't tell me any more than that, so I have no idea what's causing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Ruby 中,以大写字母开头的变量是常量。您可以重新分配一个常量,但这会导致 Ruby 发出警告。但不是在方法内部:
“Ruby 假设方法旨在被多次调用;如果您可以在方法中分配给常量,则该方法将在第一次调用后的每次调用时发出警告。因此,这是不允许的”。 (《Ruby 编程语言》,D. Flanagan 和 Y. Matsumoto,2008 年,第 94 页)
A variable starting with a capital is a constant in Ruby. You can reassign a constant, but it will cause Ruby to issue a warning. But not inside a method:
"Ruby assumes that methods are intended to be invoked more then once; if you could assign to a constant in a method, that method would issue warnings on every invocation after the first. So, this is simply not allowed." (The Ruby Programming Language, D. Flanagan & Y. Matsumoto, 2008, p.94)
尝试使用实例变量(使用
@
):Try using instance variables (with
@
):在 Ruby 中,带有大写字母的变量是常量。您将
MODE
设置为 0,但随后在方法beginSearch
中,将MODE
设置为 2,而您不能像那样执行此操作MODE
是一个常量。In Ruby, variables that being with a capital letter are constant. You set
MODE
to 0, but then in the methodbeginSearch
, you setMODE
to 2, which you can't do asMODE
is a constant.