What is Ruby's self?

Article target

What is self? What is a class method? I somehow understand the class and instance

What to explain in this article

--What is self? --What is an object? --Self in various places (inside class, outside class, inside instance method, inside class method, etc.)

General description of self

self is the object itself

Even if I was told, it didn't come to my mind. However, I think that's true now that I've fallen in love with it.

What is an object?

Let's first understand objects. In Ruby, everything is an object.

--String object --Numerical object --Array object --Hash object etc.

In the real world, we treat all kinds of things such as people, things, and animals as objects.

Difference between object and instance

The difference between an object and an instance was explained in an easy-to-understand manner on the following site, so please read it if you are interested. In a word ** An object created from a class is called an instance ** is.

I understand that the difference between class instance objects makes me feel like a god

Instance generation

Class name.new

Instance generation


class Sample
end

p Sample.new #=> #<Sample:0x00007fe79b835240>

You have created an instance.

About self

So far we've been talking about instances and objects, but finally we're going to put one foot into self. For the time being, let's create an appropriate rb file and execute it. Or try typing irb in the terminal and then typing self. (You can't use it unless you have Ruby installed. If you don't get the version information by typing ruby -v, it's not installed, so please install it.)

sample.rb


  p self
  #=> main

The main thing came out. What is main?

In a word ** main is an instance that exists at the top level and is an instance of the Object class. ** ** it's difficult.

I will explain it firmly. Let's start with the Object class.

Object class

The Object class is a class that is at the actual vertex (parent) of the class. (Actually, there is another class above, but I will omit it here.) The class has a hierarchical structure, and the parent class such as the string class is the Object class. (You can get your own class with the class method and the parent class with the superclass method.)

p "String".class #=> String
p String.superclass #=> Object

Top level

Next is the top level, which is outside the class and module definitions. (I won't talk about modules in this article. Think of them as restricted classes.)

Top level


#from here
#
#
#
#This is the top level
class Sample
  #In class
end
#from here
#
#
#
#Top level so far
module SampleModule
  #In the module
end
#from here
#
#
#
#Top level so far

And it is also the top level when you hit irb at the terminal. When you type irb in the terminal irb(main):001:0> It will be. You can see that this is the top level, and that there is main after irb.

Also, if you check the self class at the top level

p self       #=> main
p self.class #=> Object

You can see that the top-level self (main) class is Object.

Returning to what I said earlier main is an instance that exists at the top level and is an instance of the Object class. It was . this is

The execution result of the p method at the top level was p self # => main. And it was p self.class # => Object And self refers to the object itself (instance itself).

You can also see from.

The reason why you can suddenly execute p methods etc. at the top level is because main is an instance of the Object class! (The correct answer is that it can be executed because the Kernel module is included in the Object class, but it is omitted here.)

Self in class

Next, let's look at self in the class.

Self in class


class Sample
  p self #=> Sample
end

self was the object itself. Therefore, it represents the class object itself in the class.

Self in instance method

Self in the instance method represents the instance itself (the object itself).

Self in instance method


class Sample
  def hoge
    p self
  end
end
sample = Sample.new
sample.hoge #=> #<Sample:0x00007f8524034f70>

By the way, when Ruby calls a method, it implicitly calls the method for self. (Call the method for self without permission.)

What does that mean

class Person
  def greeting
    p self
    hello
  end

  def hello
    p "hello"
  end
end

person = Person.new
person.greeting #=> #<Person:0x00007f9937848a28>
                #=> "hello"

The same thing is as follows.

class Person
  def greeting
    p self 
    self.hello
  end

  def hello
    p "hello"
  end
end

person = Person.new
person.greeting #=> #<Person:0x00007f9937848a28>
                #=> "hello"

Did you notice what's different? That's right. The call to hello in the greeting method is preceded by self. Actually, this self. Is the same with or without it. I think that it is this specification because it is difficult to add self every time a method is called.

At this time, self in the greeting method is the instance of the Person class itself, so the hello method is called for that instance. (self.helloin thegreeting method and top-level person.hello have the same result.)

Class method self

Self in the class method also represents the object itself.

Self in class method


class Person
  def self.greeting
    p self
  end
end

Person.greeting #=> Person

Person is being returned.

Of course, self in this method definition part also represents the object itself, but self in the method definition location is a bit strange, isn't it?

def self.greeting #← This self
end

A class method is one of the singular methods. So what is a singular method?

Singular method

Singular methods define methods for individual objects (instances) regardless of the class.

morning = "good morning"
def morning.greeting
  p self
end

morning.greeting #=> "good morning"

What's going on with this? First, with morning =" good morning ", the character string "good morning" is assigned to the variable (object) called morning. After that, the greeting method is defined for the morning object. In the greeting method, the p method returns self. In this case, self is a string object called "good morning" The string "good morning" is output.

This form is a singular method.

It's the same as the class method definition method.

Class method definition


class Person
  def self.greeting
  end
end

Compared with the above code, def 〇 〇. The definition method is the same like the method name. And since self at this time was Person

Class method definition


class Person
  def Person.greeting
  end
end

You can also write like this.

Finally

I tried using self in various places. I hope you can understand that self represents object confidence.

After all, if you move the code yourself and verify it, your understanding will increase. If you have any questions, please let us know in the comments.

reference

Rubima http://i.loveruby.net/ja/rhg/book/minimum.html

Recommended Posts

What is Ruby's self?
What is self
What is Ruby's attr_accessor?
What is Docker?
What is null? ]
What is java
What is Keycloak
What is Jackson?
What is Docker
What is Jenkins
What is ArgumentMatcher?
What is IM-Juggling?
What is params
What is SLF4J?
What is Facade? ??
What is Java <>?
What is Gradle?
What is POJO
What is Java
What is centOS
What is RubyGem?
What is programming?
What is before_action?
What is Docker
What is Byte?
What is Tomcat
What is `docker-compose up`?
What is a constructor?
What is hard coding?
What is a stream
What is Java Encapsulation?
What is permission denied?
What is instance control?
What is an initializer?
What is Spring Tools 4
What is an operator?
What is object orientation?
What is Guava's @VisibleForTesting?
What is MVC model?
What is an annotation?
What is Java technology?
What is Java API-java
What is @ (instance variable)?
What is Gradle's Artifact?
What is JPA Auditing?
[Swift] What is dismiss?
[Java] What is flatMap?
What is a Servlet?
What is web development?
[Java] What is JavaBeans?
[Android] What is Context? ??
[Java] What is ArrayList?
[Ruby] What is true?
Understanding ruby's "|| =" specification and what is Rails presence method?
What is object-oriented after all?
What is HttpSession session = request.getSession ();
What is Java Assertion? Summary.
What is DI (Dependency Injection)
What is a wrapper class?
What is object-oriented programming? ~ Beginners ~
What is a boolean type?