chell
chell

Reputation: 7866

In ruby what is this type of definition: self.class.method

I am a NOOB trying to understand some 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

Upvotes: 4

Views: 268

Answers (3)

Pedro Rolo
Pedro Rolo

Reputation: 29960

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

This code part is being evaluated in the Class Object scope because of the class << self statement. Thus current_section is being defined as a class method, invokable as Myclass.current_section.

def current_section()
  self.class.current_section
end

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

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

Upvotes: 1

undur_gongor
undur_gongor

Reputation: 15954

It forwards the message (method call request) received by the object to the corresponding 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 h's method, it looks up h's class (MyClass) and invokes the method current_section of that class.

So, by the definitions above, every object of the class MyClass has a method current_section which is routed to the central current_section of the class.

The definition of the class methods in your question is just using a different syntax for doing the same: adding a method to the class object.

Upvotes: 1

user1179942
user1179942

Reputation: 391

self returns the the current object.

self.class returns the class of current object.

self.class.current_section invokes the method of the class of current object (that method called current_section).

 def current_section()
    p self
    p self.class
 end

 current_section()

Upvotes: 3

Related Questions