In ruby, what is this definition: self.class.method

I am NOOB trying to understand some kind of code.

What does this self.class.current_section do?

class MyClass class << self def current_section(*section) if section.empty? @current_section else @current_section = section[0] end end end def current_section() self.class.current_section end def current_section=(section) self.class.current_section(section) end end 
+4
source share
3 answers

It forwards the message (method call request) received by the object to the appropriate class.

Say you have a class

 class MyClass def MyClass.current_section puts "I'm the class method." end def current_section self.class.current_section end end h = MyClass.new h.current_section # outputs "I'm the class method." 

Calling the h method, it searches for the class h ( MyClass ) and calls the current_section method of this class.

Thus, according to the above definitions, each object of the MyClass class has a current_section method, which is directed to the central current_section this class.

Defining class methods in your question is simply using a different syntax for this: adding a method to a class object.

+1
source

self returns the current object.

self.class returns the class of the current object.

self.class.current_section calls the class method of the current object (this method is called current_section ).

  def current_section() p self p self.class end current_section() 
+3
source
 class << self def current_section(*section) if section.empty? @current_section else @current_section = section[0] end end end 

This piece of code is evaluated in the scope of the class object due to the class << self statement. Thus, current_section is defined as a class method, invokable as Myclass.current_section.

 def current_section() self.class.current_section end 

This part is just an instance method definition, and thus self is an instance of the Myclass object.

self.class gets the class of such an instance, thus Myclass , and the current_section method of the class is called.

+1
source

Source: https://habr.com/ru/post/1394367/


All Articles