summaryrefslogtreecommitdiff
path: root/ruby
diff options
context:
space:
mode:
Diffstat (limited to 'ruby')
-rwxr-xr-xruby/csv.rb62
-rw-r--r--ruby/mycsv.txt3
2 files changed, 65 insertions, 0 deletions
diff --git a/ruby/csv.rb b/ruby/csv.rb
new file mode 100755
index 0000000..c48a11a
--- /dev/null
+++ b/ruby/csv.rb
@@ -0,0 +1,62 @@
+#!/usr/bin/env ruby
+
+
+module Csv
+ class CsvRow
+ def initialize keys, values
+ @content = Hash[]
+ keys.each do |k|
+ @content[k] = values[keys.index(k)]
+ end
+ end
+
+ def method_missing name, *args
+ @content[name.to_s]
+ end
+ end
+
+ 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 << row.chomp.split(',')
+ end
+ end
+
+ def each
+ @csv_contents.each {|line| yield CsvRow.new(@headers, line)}
+ end
+ end
+end
+
+class MyCsv
+ include Csv
+ acts_as_csv
+end
+
+csv = MyCsv.new
+csv.each {|row| puts row.one}
+puts
+csv.each {|row| puts row.two}
+puts
+csv.each {|row| puts row.three}
diff --git a/ruby/mycsv.txt b/ruby/mycsv.txt
new file mode 100644
index 0000000..2987c6a
--- /dev/null
+++ b/ruby/mycsv.txt
@@ -0,0 +1,3 @@
+one,two,three
+lions,tigers,leopards
+tanks,helicopters,submarines