self can point to both a class and an instance.
For me, the image that points to an instance was stronger, but I recently learned that it points to a class, so I summarized it. I've heard that "ruby is the same as this in java", but I still don't know if it's exactly the same. I forgot this in Java now.
class ClassA
def foo #Instance method
puts "ins_foo"
puts self #This self is an instance(Instance of ClassA)Point to
end
def self.foo #Class method(This self is the class itself(ClassA)Point to)
puts "self_foo"
puts self #This self is the class itself(ClassA)Point to
end
end
ClassA.foo
# self_foo
# ClassA #Pointing to a class
ClassA.new.foo
# ins_foo
# #<ClassA:0x00007f93108144d0> #Pointing to an instance
I've read that when defining a class method, add self.
, but that self refers to the class.
Recommended Posts