开发者

undefined variable error

开发者 https://www.devze.com 2023-03-20 21:48 出处:网络
I am creating a class, then trying to do some operations inside it, but for some reason Ruby cant see the class var开发者_Go百科iables I defined at the top, any idea why?

I am creating a class, then trying to do some operations inside it, but for some reason Ruby cant see the class var开发者_Go百科iables I defined at the top, any idea why?

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

Thanks


Class variables must be prefixed with @@, so you need to rename your class variables. For example, attr_hash needs to be renamed @@attr_hash, both in the class body and in start.

BTW, to prevent overwriting the variables every time, you could do this:

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

This has the effect that parseHashFormFile is only called when @@attr_hash contains nil.


You're not creating instance variables as you think you are. Refer to http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby for a description on how instance and class variables work in Ruby.


The way you've defined them makes them local to the area outside the functions. This is just a basic scope issue - easy to fix.

Class variables start with @@, as in @@BASE_URL. See variable scope reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消