输出ruby方法的来源

tes*_*ter 4 ruby metaprogramming

假设我用一个方法创建一个类.

class A
  def test
    puts 'test'
  end
end
Run Code Online (Sandbox Code Playgroud)

我想知道里面发生了什么test.我想按字面意思输出:

def test
  puts 'test'
end
Run Code Online (Sandbox Code Playgroud)

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

kri*_*ard 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)
Run Code Online (Sandbox Code Playgroud)

然后跑ruby myfile.rb,你会看到:

def test
   return 'test'
end
Run Code Online (Sandbox Code Playgroud)

  • @KaiKönig你可以让它更容易,使用它:`Pry :: Method.from_str("A#test").source` (2认同)