I have this Ruby code where I try to implement the Singleton pattern manually:
class A
@a = A.new
def self.instance
p 'initialized'
@a
end
private_class_method :new
end
A.instance #=> prints 'initialized'
Unfortunately, the object will be created before A.instance is even called. To avoid this, I thought of changing the code:
class A
@a = nil
def self.instance
p 'initialized'
@a ||= A.new
end
private_class_method :new
end
A.instance
I get "private method `new' called for A:Class (NoMethodError)" error though. This is very puzzling, why do I get this error in the second example and not in the first? The only difference is that in the second example .new is called in a class method definition. I deliberately put private_class_method on the bottom so this kind of error is prevented (putting it on the top will give the error for both examples). Btw, I'm aware this will work if I change @a from being a class instance variable to a class variable (to start with @@). I don't understand why this would work, since I know instance variables are relative to SELF and SELF is the class, both where I initialize @a to nil and where I lazy instantiate it in self.instance.