Skip to content

Instantly share code, notes, and snippets.

@ponkore
Created April 12, 2012 12:00
Show Gist options
  • Save ponkore/2366827 to your computer and use it in GitHub Desktop.
Save ponkore/2366827 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Ruby 3rd)
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
module ActsAsCsv
class CsvRow
def initialize(headers, arr)
@headers = headers
@arr = arr
end
def method_missing(name, *args)
@arr[@headers.index(name.to_s)] # name.class == Symbol なので、.to_s が必要
end
end
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
def read
@csv_contents = []
filename = self.class.to_s.downcase + '.txt'
file = File.new(filename)
@headers = file.gets.chomp.split(', ')
file.each do |row|
@csv_contents << CsvRow.new(@headers, row.chomp.split(', '))
end
end
def each
@csv_contents.each do |csv_row|
yield(csv_row)
end
end
attr_accessor :headers, :csv_contents
def initialize
read
end
end
end
class RubyCsv # no inheritance! You can mix it in
include ActsAsCsv
acts_as_csv
end
m = RubyCsv.new
# puts m.headers.inspect
# puts m.csv_contents.inspect
m.each {|row| puts row.one}
bash$ cat rubycsv.txt
one, two
lions, tigers
bash$ ./f.rb
lions
bash$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment