2012-02-02 3 views
4

나는 어떤 코드를 이해하려고 노력하는 사람입니다.루비에서는 다음과 같은 정의가 있습니다 : self.class.method

이 self.class.current_section의 기능은 무엇입니까?

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 

답변

1

개체에서 수신 한 메시지 (메서드 호출 요청)를 해당 클래스로 전달합니다.

당신이 클래스 h 호출

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." 

이 말의 클래스 (MyClass)의 방법을, 그것은 h을 보이는 '그 클래스의 방법 current_section를 호출합니다.

따라서 위의 정의에 따라 클래스 MyClass의 모든 객체에는 클래스 current_section으로 라우팅되는 current_section 메소드가 있습니다.

질문에있는 클래스 메소드의 정의는 클래스 객체에 메소드를 추가하는 것과 같이 동일한 구문을 사용하는 다른 구문을 사용하는 것입니다.

3

self은 현재 개체를 반환합니다.

self.class은 현재 개체의 클래스를 반환합니다.

self.class.current_section은 현재 개체 클래스의 메서드 (current_section이라고하는 메서드)를 호출합니다.

def current_section() 
    p self 
    p self.class 
end 

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

이 코드 부분은 class << self 문 때문에 클래스 개체 범위에서 평가됩니다. 따라서 current_section이 일부 인스턴스에있어서 단지 정의 Myclass.current_section.

def current_section() 
    self.class.current_section 
end 

같은 호출 가능한, 클래스 방법으로 정의된다되고, 따라서 selfMyclass는 개체의 인스턴스이다.

self.class은 그러한 인스턴스의 클래스를 가져옵니다 (따라서 Myclass). 클래스의 current_section 메소드가 호출됩니다.

관련 문제