From: Robert Klemme Date: 2004-07-14T18:07:20+09:00 Subject: Re: Printing contents of a method "Dave Thomas" schrieb im Newsbeitrag news:2F308146-D4FE-11D8-B4D9-000A95676A62@pragprog.com... > > On Jul 13, 2004, at 13:43, Nate Smith wrote: > > > On Tue, 2004-07-13 at 14:24, Dave Thomas wrote: > >>>> Does anyone know how to actually print (as a string) the contents > >>>> of a > >>>> given method? I've googled and searched books, to no avail. Thanks > >>>> much > >>>> for any help > >> > >> Might SCRIPT_LINES help? (if the method is loaded into your program > >> after it starts) > > > > Forgive me if I sound stupid, but what is SCRIPT_LINES? I search google > > for it and it only came up with Perl references, and a couple of emails > > that you wrote which had the word in it. Thanks! > > > > Here's some stuff from the new pickaxe: > > SCRIPT_LINES__ (Hash) > > If a constant SCRIPT_LINES__ is defined and references a Hash at the > time Ruby is compiling code, Ruby will store an entry containing the > contents of each file it parses, with the file�s name as the key and an > array of strings as the value. See Kernel.require on page ?? for an > example. > > and then over in Kernel.require: > > The SCRIPT_LINES__ constant can be used to capture the source of code > read using require. > > SCRIPT_LINES__ = {} > require 'code/scriptlines' > puts "Files: #{SCRIPT_LINES__.keys.join(', ')}" > SCRIPT_LINES__['./code/scriptlines.rb'].each do |line| > puts "Source: #{line}" > end > > produces: > > 3/8 Files: ./code/scriptlines.rb, > /Users/dave/ruby1.8/lib/ruby/1.8/rational.rb > Source: require 'rational' > Source: > Source: puts Rational(1,2)*Rational(3,4) > > (where code/scriptlines.rb does indeed contain the three lines of code > listed above). But still at best you get the original code of methods when they were defined. If someone overrides it, you're lost. A C extension that can recreate Ruby from a given method would be a safer approach IMHO. (If that's possible, that is.) Kind regards robert