Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the source of a ruby method

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?

like image 952
tester Avatar asked Feb 19 '23 07:02

tester


1 Answers

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
like image 192
krichard Avatar answered Feb 27 '23 10:02

krichard