4

假设我创建了一个包含方法的类。

class A
  def test
    puts 'test'
  end
end

我想知道里面发生了什么test。我想从字面上输出:

def test
  puts 'test'
end

有没有办法在字符串中输出方法的来源?

4

1 回答 1

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
于 2012-12-04T09:02:06.813 回答