2012-12-04 2 views
4

거기에 메소드가 포함 된 클래스를 만듭니다.루비 메서드의 소스를 출력하십시오.

class A 
    def test 
    puts 'test' 
    end 
end 

test의 내용을 알고 싶습니다. 나는 문자 그대로 출력하고 싶다.

def test 
    puts 'test' 
end 

문자열의 메소드 소스를 출력하는 방법은 없습니까?

+0

이 명확하지 않다 "나는 시험의 내부에 어떤 일이 일어나는지 알고 싶어합니다. " 디버거에서 메서드를 단일 단계로 실행 하시겠습니까? –

답변

8

당신은 그런 ruby myfile.rb를 실행하는 방법

# myfile.rb 
require 'pry' 
class A 
    def test 
    return 'test' 
    end 
end 
puts Pry::Method(A.new.method(:test)).source  #(1) 
# or as suggested in the comments 
puts Pry::Method.from_str("A#test").source  #(2) 
# uses less cpu cycles than #(1) because it does not call initialize - see comments 
puts Pry::Method(A.allocate.method(:test)).source #(3) 
# does not use memory to allocate class as #(1) and #(3) do 
puts Pry::Method(A.instance_method(:test)).source  #(4) 

을 볼 수 Pry을 사용할 수 있으며 표시됩니다

def test 
    return 'test' 
end 
+0

'binding.pry'를 사용할 필요가 없습니다.'pry' 명령을 실행하고'load "a.rb"를 사용하고'show-method A # test' 메소드를 사용하십시오. 표시됩니다. 다음은 소스 코드입니다 : [Pry 's show-source] ( – vgoff

+0

) - 그게 더 쉽습니다. – krichard

+2

@ KaiKönig 당신은 쉽게 이것을 만들 수 있습니다 :'Pry :: Method.from_str ("A # test"). 소스' – horseyguy

관련 문제