From: "Ara.T.Howard" Date: 2005-08-13T00:18:13+09:00 Subject: Re: Re-reading a portion of a source file from a specific point On Wed, 10 Aug 2005, Berger, Daniel wrote: > Hi all, > >> From within a Ruby program, is there a way to get Ruby to re-read itself > from a specific part of the file? Let me explain. Say I have a method > "foo". I would like "foo" to slurp the rest of the script into memory > and write it to a file, possibly a temp file. > > For example: > > 1: puts "Hello World" > 2: foo() > 3: puts "How's it going?" > > In this script I would like lines 2 and 3 (or possibly just line 3 - I'm > not sure yet), but NOT line 1, read into memory and written to a file > (by the foo method). I thought perhaps there were some tricks I could > use with __DATA__, __END__ or __FILE__, but I wasn't sure. > > Any ideas? > > Regards, > > Dan one approach: harp:~ > cat a.rb require 'tempfile' require 'stringio' def record opts = {} getopt = lambda do |o| catch('opt') do [o, o.to_s, o.to_s.intern].each{|k| throw 'opt', opts[k] if opts.has_key? k} throw 'opt', nil end end file = getopt['file'] or raise ArgumentError, 'no file' a = getopt['start'] or raise ArgumentError, 'no start' b = getopt['end'] || -1 into = getopt['into'] || Tempfile::new(File::basename(file)) into << IO::readlines(file)[a .. b].join into.flush if into.respond_to?('flush') into.rewind if into.respond_to?('rewind') into end puts '---' tmp = record 'file' => __FILE__, 'start' => __LINE__ print tmp.read puts '---' tmp = record 'file' => __FILE__, 'start' => -2, 'end' => -1, 'into' => StringIO::new print tmp.read harp:~ > ruby a.rb --- print tmp.read puts '---' tmp = record 'file' => __FILE__, 'start' => -2, 'end' => -1, 'into' => StringIO::new print tmp.read --- tmp = record 'file' => __FILE__, 'start' => -2, 'end' => -1, 'into' => StringIO::new print tmp.read cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | Your life dwells amoung the causes of death | Like a lamp standing in a strong breeze. --Nagarjuna ===============================================================================