Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =begin
- It's day 3, and the last day of ruby! Has everyone can see, it's getting really hard! Well, if you paid attention since the begining it's not to hard. I don't know if I will share another exercise or not, but anyway. I hope everyone enjoy ;)
- =end
- =begin
- the file is like this
- ----------------rubycsv.txt-----------
- one, two
- lions, tigers
- cats, dogs
- bird, fish
- --------------------------------------
- =end
- module ActsAsCsv
- def self.included(base)
- base.extend ClassMethods
- end
- module ClassMethods
- def acts_as_csv
- include InstanceMethods
- end
- end
- module InstanceMethods
- attr_accessor :headers, :csv_contents
- def initialize
- read
- end
- 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 { |row| yield row }
- end
- class CsvRow
- def initialize headers, row
- @headers = headers
- @row = row
- end
- def method_missing name, *args, &block
- index = @headers.index(name.to_s)
- if index
- @row[index]
- else
- "Can not find"
- end
- end
- 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}, #{row.two}" }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement