I am creating a class, then trying to do some operations inside it, but for some reason Ruby cant see the class variables 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_hashneeds to be renamed@@attr_hash, both in the class body and instart.BTW, to prevent overwriting the variables every time, you could do this:
This has the effect that
parseHashFormFileis only called when@@attr_hashcontainsnil.