I'm not sure I understood what you want to do. Do you want to write the 
modified data to another file or to the same file?

In the first case, all you need to do is the following (in file rw1.rb):

File.open('output_file','w'){|f|
 FixedLengthRecordFile.open('test1.abc', [2, 3, 12, 7, 2, 1, 2, 1, 4, 2, 
1, 2, 1, 4, 10]) do |row|
f.write 
"#{row[1]}\t#{row[2]}\t#{row[3]}\t#{row[8]}-#{row[4]}-#{row[6]}\t#{row[13]}-#{row[9]}-#{row[11]}\t#{row[14]}\n"
 end
}

Instead, if you want to write the data back to the same file, you could 
write your FixedLengthRecordFile.open method as

def FixedLengthRecordFile.open(filename, field_sizes)
    if field_sizes.nil? or field_sizes.empty?
      raise ArgumentError, "Empty field sizes not allowed!"
    end

    field_pattern = 'a' + field_sizes.join('a')
    File.open(filename, 'r+'){|file|
      IO.foreach(filename) do |line|
        record = line.chomp.unpack(field_pattern)
        record.map { |f| f.strip! }
      	file.write(yield(record))
      end
    }
end

or you could write

def FixedLengthRecordFile.open(filename, field_sizes)

    if field_sizes.nil? or field_sizes.empty?
      raise ArgumentError, "Empty field sizes not allowed!"
    end

    field_pattern = 'a' + field_sizes.join('a')
    lines=File.readlines(filename)
    File.open(filename, 'w'){|file|
      lines.each do |line|
        record = line.chomp.unpack(field_pattern)
        record.map { |f| f.strip! }
      	file.write(yield(record))
      end
    }
end

I don't know whether this approach would lead to worst performances, 
given the length of your files.

In both cases, the block you pass to the open method should return the 
string to write:
  FixedLengthRecordFile.open('test1.abc', [2, 3, 12, 7, 2, 1, 2, 1, 4, 
2,
1, 2, 1, 4, 10]) do |row|
"#{row[1]}\t#{row[2]}\t#{row[3]}\t#{row[8]}-#{row[4]}-#{row[6]}\t#{row[13]}-#{row[9]}-#{row[11]}\t#{row[14]}\n"
end

A couple of notes:
* you need to add the "\n" at the end of your string in the rw1 file, 
otherwise all the rows in the original file will be written as one line
* this method will only work when all the lines of the data file have 
the same structure (for example, it won't work with the first line of 
your data file example above)


-- 
Posted via http://www.ruby-forum.com/.