假设我用一个方法创建一个类。
class A
def test
puts 'test'
end
end
我想知道test
内部发生了什么。我想输出:
def test
puts 'test'
end
有没有办法在字符串中输出方法的来源?
答案 0 :(得分:8)
您可以使用Pry查看方法
# 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)
然后运行ruby myfile.rb
,您会看到:
def test
return 'test'
end