【问题标题】:Dynamic constant assignment in Ruby [duplicate]Ruby中的动态常量赋值[重复]
【发布时间】:2016-02-11 18:07:09
【问题描述】:

下面显示的是一个 ruby​​ 代码。

def parse_file(file)
  parsed_data = {}
  TOTAL = []
  Maths = []
  Physics = []
  Chemistry = []
  read_lines(file) { |line|
    arr=l.split
    if l.match(/TOTAL/i)
      TOTAL = arr[1].to_i
    end
    if l.match(/maths/i)
      Maths = arr[1].to_i
    end
    if l.match(/physics/i)
      Physics = arr[1].to_i
    end
    if l.match(/chemistry/i)
      Chemistry = arr[1].to_i
    end
  }
  if TOTAL != Maths + Physics + Chemistry && TOTAL != 0
    parsed_data[:not_matched] = "True"
  end
  return parsed_data
end

它给出了多个“动态常量赋值”错误:

-:3: dynamic constant assignment
      TOTAL = []
             ^
-:4: dynamic constant assignment
      Maths = []
             ^
-:5: dynamic constant assignment
      Physics = []
               ^
-:6: dynamic constant assignment
      Chemistry = []
                 ^
-:10: dynamic constant assignment
          TOTAL = arr[1].to_i
                 ^
-:13: dynamic constant assignment
          Maths = arr[1].to_i
                 ^
-:16: dynamic constant assignment
          Physics = arr[1].to_i
                   ^
-:19: dynamic constant assignment
          Chemistry = arr[1].to_i
                     ^

我可以做哪些改变,以免影响我的意图?

【问题讨论】:

  • 我以前从未遇到过这个错误,我很惊讶 Ruby 以 SyntaxError 失败。运行代码时,我会预料到通常的“已经初始化的常量”警告。
  • @Stefan 我认为如果在解析阶段可以检测到,他们希望将其设为SyntaxError
  • @sawa 当然,尽早检测代码不一致是一个很好的帮助。但是提出 syntax 错误似乎有点苛刻 IMO。此外,它甚至禁止在方法中使用 Foo = 1 unless defined? Foo 之类的代码。
  • 除了使用常量名作为变量名之外,这段代码很奇怪。变量初始化为空数组,然后设置为整数。

标签: ruby constants


【解决方案1】:

将其更改为局部变量,例如total

【讨论】:

    【解决方案2】:

    错误提示“动态常量分配”。 CAPITAL_LETTERS 被视为常量,不得在代码中动态分配新值。

    因此,最好将TOTAL 更改为total 之类的局部变量

    【讨论】:

    • 你的回答自相矛盾。根据定义,变量不是常量,常量不是变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    相关资源
    最近更新 更多