Output the source of a ruby method

血红的双手。 提交于 2020-01-01 05:50:10

问题


Say I make a class with a method in it.

class A
  def test
    puts 'test'
  end
end

I want to know what goes on inside of test. I want to literally output:

def test
  puts 'test'
end

Is there any way to output the source of a method in a string?


回答1:


You can use Pry to view methods

# 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)

Then run ruby myfile.rb and you will see:

def test
   return 'test'
end


来源:https://stackoverflow.com/questions/13698768/output-the-source-of-a-ruby-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!