输出 ruby 方法的源代码



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

class A
  def test
    puts 'test'
  end
end

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

def test
  puts 'test'
end

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

您可以使用 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

最新更新