Last active
December 18, 2015 13:29
-
-
Save jeffreyiacono/5790029 to your computer and use it in GitHub Desktop.
fun with CSVs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
moved to: https://github.com/jeffreyiacono/extended_csv