2

I'm trying to understand what type of variable @bar is, in the code below.

class Foo
  @bar = 7       # defined outside of initialize method

  def self.bar   # defined on the class, not as an instance method
    @bar
  end
end
  • It uses the single @ notation, which makes it an instance variable
  • But because it's defined outside of an initialize method, I think it becomes an instance variable on the Foo class, not an instance variable on instances of Foo

If ^^^ is correct, then I guess I just want to understand the possible uses of this. I was doing something like this recently in order to memoize something similar to the following:

class FileCache
  @cache = {}
  def self.read(filename)
    @cache[filename] ||= File.read(filename)
  end
end

The intention of the FileCache::read method is prevent going out to the file system every time you want to read a given file. It seems to work with @cache defined on the class (rather than via attr_reader or inside of initialize), and I just want to make sure I understand why.

It seems like what's happening is that @cache becomes an instance variable of the Singleton object FileCache, which itself is an instance of the Class class.

Is ^^^ anywhere near a correct understanding? I've also tried reading this artcile. Looking for someone who knows to confirm/deny my understanding.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • 3
    Have you see this question, I found the discussion there very helpful https://stackoverflow.com/questions/15773552/ruby-class-instance-variable-vs-class-variable – csexton Jan 29 '20 at 15:59

0 Answers0