Skip to content

Instantly share code, notes, and snippets.

@jdoig
Created November 9, 2011 19:02
Show Gist options
  • Save jdoig/1352535 to your computer and use it in GitHub Desktop.
Save jdoig/1352535 to your computer and use it in GitHub Desktop.
Total bastardization of day 3
def get_filename(obj)
filename = obj.to_s.downcase + '.txt'
end
def read_line(line)
line.chomp.split(', ')
end
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
headers = read_line(File.open(get_filename(self)).readline).each{|h| define_method(h){ @csv_contents[h]} }
end
end
module InstanceMethods
def read
filename = get_filename(self.class)
File.open(filename).each_with_index{|l,i| i == 0 ? @csv_contents = Hash[read_line(l).collect{|h| [h,[]]}] : read_line(l).each_with_index{|v,i| @csv_contents.values[i] << v}}
end
end
def row(row_number)
@csv_contents.values.collect{|c| c[row_number]}
end
attr_accessor :headers, :csv_contents
def initialize
read
end
end
class RubyCsv
include ActsAsCsv
acts_as_csv
end
csv = RubyCsv.new
csv.one.each {|row| puts row}
csv.two.each {|row| puts row}
puts csv.row(0)
@jomontanari
Copy link

While I love how succinct you can be with Ruby, I do wonder how long it would take somebody else to understand this line and if you maaaaaybe could have made it a bit more readable :)

File.open(filename).each_with_index{|l,i| i == 0 ? @csv_contents = Hash[read_line(l).collect{|h| [h,[]]}] : read_line(l).each_with_index{|v,i| @csv_contents.values[i] << v}}

@jomontanari
Copy link

Nice that you don't have to override method_missing for this though.

@jdoig
Copy link
Author

jdoig commented Nov 12, 2011

Hehe; yeah this one involved a lot of me playing with Ruby rather than writing 'good' Ruby. I particularly dislike that line as it wouldn't run if I put the ternary operator over multiple lines... It would have certainly benefited from using a do-end block rather than an in-line statement.

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