Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>An OO approach. Note that I did this when I thought you wanted blanks filled with <code>[doc_X.doc, date]</code> as opposed to <code>[X, date]</code> - for which this approach is more appropriate as it required more regexes on <code>@file_name</code>. This may be a bit verbose now but nevertheless it works and is quite readable.</p> <pre><code>require 'csv' class Upload attr_reader :file_number, :date def initialize(file_name_or_number, date) @date = date @file_number = if file_name_or_number.is_a?(String) file_name_or_number[/_(\d+)\./, 1].to_i else file_name_or_number end end def to_a [@file_number, @date] end end class UploadCollection attr_reader :uploads def initialize(input_file) # Slice off all but the first element input_data = CSV.read(input_file)[1..-1] # Create an array of Upload objects and sort by file number @uploads = input_data .map { |row| Upload.new(row[0], row[1]) } .sort_by(&amp;:file_number) end def fill_blanks! # Get the smallest and largest file number # (they're sorted this way, remember) min, max = @uploads.first.file_number, @uploads.last.file_number # Create an array of all numbers between min and max, and # remove those elements already representing a file number missing = (min..max).to_a - @uploads.map(&amp;:file_number) missing.each do |num| # Explaining how this works makes my head ache. Check out the # docs for Array#insert. @uploads.insert(num - 1, Upload.new(num, @uploads[num-2].date)) end # Non-ambiguous return value true end def to_a @uploads.map(&amp;:to_a) end def write_csv(file_path) CSV.open(file_path, 'wb') do |csv| csv &lt;&lt; ['file_number', 'date'] # Headers to_a.each { |u| csv &lt;&lt; u } end end end file = 'fnames.csv' collection = UploadCollection.new(file) collection.fill_blanks! puts collection.to_a collection.write_csv('out.csv') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload