Ruby 模块语法错误

发布于 2025-01-08 08:43:48 字数 211 浏览 0 评论 0原文

我在理解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傲影 2025-01-15 08:43:48

在 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)

小红帽 2025-01-15 08:43:48

尝试使用实例变量(使用 @):

module Mod
  def Mod.begin_search
    # set @mode to 2. Instance variables are preserved among methods.
    @mode = 2
  end
  def Mod.mode
    # set @mode to 0 if it's not initialized yet.
    @mode ||= 0
  end
  def Mod.time_for_search
    # use Mod.mode to get @mode, granted it's set (0, 2 or whatever)
    mode == 2
  end
end

# Testing...
puts Mod.mode
#=> 0

puts Mod.time_for_search
#=> false

Mod.begin_search
puts Mod.mode
#=> 2

puts Mod.time_for_search
#=> true

Try using instance variables (with @):

module Mod
  def Mod.begin_search
    # set @mode to 2. Instance variables are preserved among methods.
    @mode = 2
  end
  def Mod.mode
    # set @mode to 0 if it's not initialized yet.
    @mode ||= 0
  end
  def Mod.time_for_search
    # use Mod.mode to get @mode, granted it's set (0, 2 or whatever)
    mode == 2
  end
end

# Testing...
puts Mod.mode
#=> 0

puts Mod.time_for_search
#=> false

Mod.begin_search
puts Mod.mode
#=> 2

puts Mod.time_for_search
#=> true
虐人心 2025-01-15 08:43:48

在 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 method beginSearch, you set MODE to 2, which you can't do as MODE is a constant.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文