Skip to content

Instantly share code, notes, and snippets.

@draftcode
Created March 2, 2013 13:29
Show Gist options
  • Select an option

  • Save draftcode/5070964 to your computer and use it in GitHub Desktop.

Select an option

Save draftcode/5070964 to your computer and use it in GitHub Desktop.
module ActAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def act_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(self, row.chomp.split(', '))
end
end
def each
@csv_contents.each {|row| yield row}
end
attr_accessor :headers, :csv_contents
def initialize
read
end
end
class CsvRow
def method_missing(name, *args)
@row[@instance.headers.index(name.to_s)]
end
def initialize(instance, row)
@instance = instance
@row = row
end
end
end
class RubyCsv
include ActAsCsv
act_as_csv
end
csv = RubyCsv.new
csv.each {|row| puts row.one}
while line = ARGF.gets
puts line if line =~ /ARGF/
end
class Tree
attr_accessor :children, :node_name
def initialize(name, hash)
@node_name = name
@children = hash.map do |name, h|
Tree.new(name, h)
end
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
ruby_tree = Tree.new('grandpa', {'dad' => {'child 1' => [], 'child 2' => []},
'uncle' => {'child 3' => [], 'child 4' => []}})
puts "Visiting a node"
ruby_tree.visit {|node| puts node.node_name}
puts
puts "Visiting entire tree"
ruby_tree.visit_all {|node| puts node.node_name}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment