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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With