Subject: Re: Printing contents of a method
From: Dave Thomas <dave@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).
Cheers
Dave