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 に答える