I'm currently working with extremely large fixed width files, sometimes well over a million lines. I have written a method that can write over the files based on a set of parameters, but I think there has to be a more efficient way to accomplish this. The current code I'm using is:
def self.writefiles(file_name, positions, update_value)
@file_name = file_name
@positions = positions.to_i
@update_value = update_value
line_number = 0
@file_contents = File.open(@file_name, 'r').readlines
while line_number < @file_contents.length
@read_file_contents = @file_contents[line_number]
@read_file_contents[@positions] = @update_value
@file_contents[line_number] = @read_file_contents
line_number += 1
end
write_over_file = File.new(@file_name, 'w')
line_number = 0
while line_number < @file_contents.length
write_over_file.write @file_contents[line_number]
line_number += 1
end
write_over_file.close
end
For example, if position 25 in the file indicated that it is an original file the value would be set to "O" and if I wanted to replace that value I would use ClassName.writefiles(filename, 140, "X") to change this position on each line. Any help on making this method more efficient would be greatly appreciated!
Thanks