Ruby pros: Please help...How to create multiple copies of Fil eA using names from FileB?


(Kurt Euler) #1

Thanks, Park. I’ll give this code a try.

I’m a newbie, but its clear I need to get a more advanced Ruby guide before I can do this level of coding (even though I’m sure its elementary) on my own.

Question: I’ve seen the “for line in file” in program samples like the one below. What’s there a reason why this line-stepping technique would not have worked in my application?

# Count the words in a file     #  1
                                #  2
filename = ARGV.shift           #  3
words = 0                       #  4
file = open(filename)           #  5
for line in file                #  6
  words += line.split.length    #  7
end                             #  8
file.close                      #  9
                                # 10
puts "Word Count: #{words}"     # 11

I appreciate your help!

-Kurt

···

-----Original Message-----
From: Park Heesob [mailto:phasis@hananet.net]
Sent: Friday, June 07, 2002 12:34 AM
To: ruby-talk@ruby-lang.org
Subject: Re: Ruby pros: Please help…How to create multiple copies of
FileA using names from FileB?

Hi,

“Kurt Euler” keuler@portal.com wrote in message
news:C47CCC6238EFD4119C5200508B95A100074AF629@cup1ex1.portal.com

All-

I’d be grateful for a jumpstart on this problem:

I have two text files “FileA” and “FileB”. FileB contains many lines, each
line has three colon delimted fields (field1, field2, field3). What I want
to do is step through FileB line-by-line, replace some text in FileA with
the values in the field2 and field3 fields of FileB, and save the modified
FileA with a file name that comes from the text in field1 of FileB.

I think you want this code, don’t you?

content = File.new(“FileA”).read
IO.foreach(“FileB”) { |x|
field = x.chop.split(’:’)
content2 = content

modify content2 here

File.new(field[0],“w+”).write(content2)
}

Park Heesob.


(Han Holl) #2

Kurt Euler wrote:

Thanks, Park. I’ll give this code a try.

I’m a newbie, but its clear I need to get a more advanced Ruby guide before I can do this level of coding (even though I’m sure its elementary) on my own.

Question: I’ve seen the “for line in file” in program samples like the one below. What’s there a reason why this line-stepping technique would not have worked in my application?

Count the words in a file # 1

                               #  2

filename = ARGV.shift # 3
words = 0 # 4
file = open(filename) # 5
for line in file # 6
words += line.split.length # 7
end # 8
file.close # 9
# 10
puts “Word Count: #{words}” # 11

I appreciate your help!

Well, ir worked for me. Maybe (if you are using a Unix variant) you
have a permission problem ?

Han Holl