class << self #or class << A
Like all instance variables, it belongs to whatever object is 'self'
at the point where the instance variable appears, and multiple
references to the same instance variable in different contexts where
self is the same, will be references to the same instance variable.
But here self is #<Class:A>. Here it really the same context/self as for
class instance variables (A).
I don't find the term "singleton variable" very helpful. All the
variables in your example are just instance variables. Calling them
"class instance variables" is sometimes useful, since there are
So, let's take an another example. After every "puts self" I put the
result.
class A
puts "Inside class"
puts self # A -> This is the self that our instance variable would be
linked to, making a "class instance variable"
def meth
puts "Inside method"
puts self # #<A:0x2ebd140>
end
def self.methc
puts "Inside class method"
puts self # A
end
class << self
puts "Inside singleton"
puts self # #<Class:A> -> and this is the self that our instance
variable would be linked to...
def meths
puts "Inside singleton method"
puts self # A
end
end
end
a = A.new
#<A:0x2ebd140>
With a being #<A:0x2ebd140>, the results are :
- A
- #<A:0x2ebd140>
- #<Class:A>
So, when defining what's usually called a "class instance variable", the
self is "A". For what I call a "singleton variable", but that you called
a "class instance variable", the self is "#<Class:A>".
To me, there's a difference, but I don't know what that "#<Class:A>" is.
It's the same thing with a self.method.
Can someone tell me how to use those @my_variable and self.method in the
following class :
class A
class << self
@my_variable
def self.my_method
end
end
# This is where I'd like to use it
end
# Or we can use it from here on a new instance or an the class itself
maybe ?
I'll sleep over it...