[Ruby] Does self refer to a class or an instance?

Conclusion

self can point to both a class and an instance.

background

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.

Experiment

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

[Ruby] Does self refer to a class or an instance?
How to check if an instance variable is defined in a Ruby class
[Ruby] Relationship between parent class and child class. The relationship between a class and an instance.
How to install Ruby on an EC2 instance on AWS
How to change a string in an array to a number in Ruby
[Self-use memo] (Ruby) class, class instance, instance
[Ruby] What is an instance?
What happens to instance variables when copying an instance with ruby
How to handle an instance
[Java] A class is an OS, and an instance is a virtual computer.
[Ruby] Class methods, instance methods, etc.
[Ruby] I want to put an array in a variable. I want to convert to an array
How to create a web server on an EC2 instance on AWS
Easy to understand the difference between Ruby instance method and class method.
I tried to make a parent class of a value object in Ruby
An implicit reference to an enclosing object held by a non-static nested class
Deploy a Node.js application to an ECS instance using the Cloud Toolkit
Why assign an ArrayList to a List
Why does Java call a file a class?
How to define an inner class bean
I get an error when I try to use "^" or "$" in ruby ​​regular expression
How to get an arbitrary digit from a number of 2 or more digits! !!
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
How to start a subscript from an arbitrary number in Ruby iterative processing