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
                     ^

我可以进行哪些更改,以免影响我的意图?

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

错误显示"动态常量赋值"。CAPITAL_LETTERS被视为常量,不得在代码中动态分配新值。

因此,最好将TOTAL更改为局部变量,例如total

相关内容

  • 没有找到相关文章

最新更新