未定义的变量错误

时间:2011-07-18 15:04:01

标签: ruby

我正在创建一个类,然后尝试在其中进行一些操作,但由于某些原因Ruby无法看到我在顶部定义的类变量,任何想法为什么?

class GoogleChart
  BASE_URL = "http://chart.apis.google.com/chart"
  URL_MAX_LENGTH = 2074 #found this online
  help_file = "help_attr_hash.txt"
  attr_file = "attr_hash.txt"
  attr_hash = nil
  help_hash = nil

  def parseHashFromFile(filename)
    return if filename == nil

    hash_array = []

    #open the file
    f = File.open(filename)

    #read each line and strip off '\r\n'
    f.each do |line|
      hash_array.push(line.chomp!)
    end

    #convert to a Hash {x => y}
    hash = Hash[*hash_array.flatten]

    return hash
  end

  def start
    attr_hash = parseHashFromFile(attr_file) ##Cant see attr_file
    help_hash = parseHashFromFile(help_file) ##Cant see help_file

    puts attr_hash
    puts help_hash
  end

  if __FILE__ == $0
    start()
  end
end

由于

3 个答案:

答案 0 :(得分:1)

类变量必须以@@为前缀,因此您需要重命名类变量。例如,attr_hash需要在类正文和@@attr_hash中重命名为start

顺便说一句,为了防止每次都覆盖变量,你可以这样做:

@@attr_hash ||= parseHashFromFile(@@attr_file)

这样做只会在parseHashFormFile包含@@attr_hash时调用nil

答案 1 :(得分:1)

您不是按照自己的想法创建实例变量。有关实例和类变量如何在Ruby中工作的描述,请参阅http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby

答案 2 :(得分:1)

您定义它们的方式使它们位于函数外部区域的本地。这只是一个基本的范围问题 - 易于修复。

类变量以@@开头,与@@BASE_URL一样。请参阅variable scope reference

相关问题