Ruby에서 메소드의 소스 코드를 쉽게 얻을 수 있습니다.
다음과 같은 가상 클래스 상상 :
class Klass
def self.foo
:foo
end
def bar
:bar
end
end
을 당신이 볼 수 있듯이,이 클래스는 두 가지 방법이 있습니다
- 클래스 메소드 .foo
- 인스턴스 메서드 #bar
을
.method
및 .instance_method
을 사용하여 프로그램에 액세스하십시오. matically :
m1 = Klass.method :foo
=> #<Method: Klass.foo>
m2 = Klass.instance_method :bar
=> #<UnboundMethod: Klass#bar>
당신은 자신의 소스 코드를 볼 수 .source
방법을 사용할 수 있습니다 :
puts m1.source
def self.foo
:foo
end
=> nil
puts m2.source
def self.bar
:bar
end
=> nil
을 루비가 열려 클래스와 동적 로딩을 가지고 있기 때문에, 당신은 또한 추가하거나 런타임에 변경 방법 할 수 있습니다. 그냥 클래스를 다시 열고 방법을 재정의 : 이전 클래스에 정의
Klass.foo
=> :foo
class Klass
def self.foo
:foobar
end
end
Klass.foo
=> :footer
다른 방법은 영향을받지 않습니다 :
Klass.bar
=> :bar
경고 : 런타임시 재정의 클래스 동작을 (또한 "라는 Monkey Patching ") 은 매우 강력한 도구이며 다소 위험 할 수도 있습니다. Ruby 의 최신 버전은 '정교화'라고하는 훨씬 더 제어 된 방식을 지원합니다.
당신은 learn more about using refinements here
에 유래에 비슷한 질문을 볼 수 http://stackoverflow.com/questions/4740684/ruby-get-source-code 또는 http://stackoverflow.com/questions/3393096/how - 소스 코드 - 메서드 - 동적 - 및 - 파일 -이 - m 또는 http://stackoverflow.com/questions/4719649/ruby-print-source를 참조하십시오. -code 또는 http://stackoverflow.com/questions/1164903/find-the-source-of-eval-code ... – mliebelt