Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # class Tree
- # attr_accessor :children, :node_name
- # def initialize(hash)
- # @children = []
- # hash.keys.each do |key|
- # @node_name = key
- # hash[key].keys.each do |childkey|
- # @children << Tree.new({ childkey => hash[key][childkey] })
- # end
- # end
- # end
- # def visit_all(&block)
- # visit &block
- # children.each {|c| c.visit_all &block}
- # end
- # def visit(&block)
- # block.call self
- # end
- # def to_s
- # puts @node_name
- # end
- # end
- # x = {"grandpa" => { "dad" => {"child 1" => {}, "child 2" => {} }, "uncle" => {"child 3" => {}, "child 4" => {} } } }
- # y = Tree.new(x)
- # y.visit_all { |c| c.to_s }
- # i = 0
- # File.open("test.txt").each { |line| puts i.to_s + " | " + line if line =~ /blue/ ; i = 1 + i }
- module ActsAsCsv
- #where should this go?
- def self.method_missing name, *args
- i = @headers.index(name)
- return if i.nil?
- @csv_contents.each do |c|
- puts c[i]
- end
- end
- def self.included(base)
- base.extend ClassMethods
- end
- def self.method_missing name, *args
- i = @headers.index(name)
- return if i.nil?
- @csv_contents.each do |c|
- puts c[i]
- end
- 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 << row.chomp.split(', ')
- 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.one
- # OUTPUT:
- #["one", "two"]
- #[["1correct", "1wrong"], ["2correct", "2wrong"], ["3correct", "3wrong"], ["4correct", "4wrong"], ["5correct", "5wrong"]]
- #./grep.rb:93: undefined method `one' for #<RubyCsv:0x3fd3e18> (NoMethodError)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement