メソッドを含むクラスを作成するとします。
class A
def test
puts 'test'
end
end
中はどうなっているのか知りたいですtest
。文字通り出力したい:
def test
puts 'test'
end
メソッドのソースを文字列で出力する方法はありますか?
メソッドを含むクラスを作成するとします。
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