Problem: Newbie with a question on file arrays and file inser tion


(Kurt Euler) #1

Thanks very much Nabu and Stehan!

Question: Can I do as you describe with Ruby 1.67? I want to make sure, since I read somewhere that you have to have at least rev 1.7 to read an entire file, but I could be mistaken. (And I thought I’d stick with 1.67, since it supposed to be the most “stable”.)

-k euler

···

-----Original Message-----
From: nobu.nokada@softhome.net [mailto:nobu.nokada@softhome.net]
Sent: Sunday, June 02, 2002 1:43 AM
To: ruby-talk@ruby-lang.org
Subject: Re: Problem: Newbie with a question on file arrays and file
insertion …

Hi,

At Sun, 2 Jun 2002 17:09:07 +0900, Stefan Schmiedl wrote:

2)- Say I have text files FileA and FileB. FileA contains a
text tag in the somewhere in it called, say,
"". How can I:

 - locate the tag <foobar> in FileA and
 - replace <foobar> with the entire contents of FileB.

 In short, I want to insert FileB in FileA where the <foobar> tag is,
 then delete the tag.

if the files are not too large, you could read them as a whole
and then just do string substitution.

a = File(“a”).read
b = File(“b”).read

a.gsub(//, b)

If “a” is large:

require 'tempfile’
require ‘ftools’

t = Tempfile.new(“foobar”)
b = nil
IO.foreach(“a”) do |line|
t.print(line.gsub(//) do
b ||= File.open(“b”) {|b| b.read}
end)
end
File.copy(t.path, “a”)

Be warned: this is written on a sunday morning before breakfast :slight_smile:

Too, except that it’s an evening here. :slight_smile:


Nobu Nakada