Let's say I create a class using the method in it.
class A def test puts 'test' end end
I want to know what happens inside test . I want to literally output:
test
def test puts 'test' end
Is there a way to output the method source to a string?
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:
ruby myfile.rb
def test return 'test' end