Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active December 18, 2015 13:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeffreyiacono/5790029 to your computer and use it in GitHub Desktop.
fun with CSVs
require 'csv'
class ExtendedCSV
attr_accessor :filepaths
def initialize filepaths
@filepaths = [*filepaths]
end
def + other_extended_csv
self.class.new self.filepaths + other_extended_csv.filepaths
end
def content
return @content if defined? @content
@content ||= []
@filepaths.each_with_index do |csv_filepath, i|
csv = CSV.parse(File.read(csv_filepath))
csv.shift unless i == 0
csv.each do |row|
@content << row
end
end
@content
end
def == other_extended_csv
content == other_extended_csv.content
end
def content_length
content.length
end
def write! outfile = nil
outfile ||= default_outfile_name
CSV.open(outfile, "wb") do |csv|
content.each do |row|
csv << row
end
end
puts "wrote #{@filepaths.length} files to #{outfile}"
end
private
def default_outfile_name
"#{Time.now.strftime("%Y%m%d%H%M%S")}_#{@filepaths.length}_files.csv"
end
end
first = ExtendedCSV.new 'first.csv'
second = ExtendedCSV.new 'second.csv'
parts = ExtendedCSV.new ['first.csv', 'second.csv']
whole = ExtendedCSV.new 'first_and_second_already_combined.csv'
# using the + operator
puts (whole == (first + second)) ? "matchy!" : "no matchy!"
# using the initializer
puts "whole contains #{whole.content_length} records"
puts "parts contain #{parts.content_length} records"
puts (whole == parts) ? "matchy!" : "no matchy!"
@jeffreyiacono
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment