summaryrefslogtreecommitdiff
path: root/ruby/csv.rb
diff options
context:
space:
mode:
authorGuillermo Ramos2012-04-01 16:49:59 +0200
committerGuillermo Ramos2012-04-01 16:50:09 +0200
commit4bbf0d67dbc7d80cb1a6f4e096263f4e1cf77878 (patch)
tree17fdeb4b296aee607fcb60b149edd3237a58e4de /ruby/csv.rb
parentd5fc25cac083e63c88a830bdcf7359f8a1dac643 (diff)
download7l-4bbf0d67dbc7d80cb1a6f4e096263f4e1cf77878.tar.gz
[Ruby] Día 3
Diffstat (limited to 'ruby/csv.rb')
-rwxr-xr-xruby/csv.rb62
1 files changed, 62 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}