From: Anurag Priyam Date: 2011-02-18T04:40:46+09:00 Subject: Re: Ruby reflection - get method definition as a string > Hi Folks - I am running some ruby tests and would like to print out > the actual test to the console or store it to a file.  The tests are > written as classes with a setup, run, and teardown method. > So here's my question: is there a way to get the class definition or > method definitions as a "string", so that I can print it out (to a > file or console)? > I know ruby supports a lot of reflection (like .methods > or .constants), but I'm not seeing how to do this. A very non-elegant, trivial way using Ruby's DATA stream ;) : # test.rb def foo puts "hi" end flag = nil DATA.tap{|x| x.rewind}.readlines.each do |line| flag = true if line =~ /^def/ puts line if flag flag = false if line =~ /^end/ end __END__ $ ruby test.rb def foo puts "hi" end Obviously you will have to come up with better heuristics to determine the end of a method. -- Anurag Priyam http://about.me/yeban/