Skip to content

Instantly share code, notes, and snippets.

@carlisgg
Created October 2, 2011 21:29
Show Gist options
  • Save carlisgg/1257988 to your computer and use it in GitHub Desktop.
Save carlisgg/1257988 to your computer and use it in GitHub Desktop.
7L7W
filename = 'text.txt'
pattern = ARGV[0]
pattern = "" if pattern == nil
File.open(filename, 'r') do |f|
lines = f.readlines
lines.each {|line| puts line if line =~ Regexp.new(pattern)}
end
class Tree
attr_accessor :children, :node_name
def initialize(structure = {})
@children = []
subtree = structure.shift
@node_name = subtree[0]
subtree[1].each {|key, value| @children.push(Tree.new({key => value}))}
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}
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
class CsvRow
attr_accessor :columns
def method_missing name, *args
@columns[name.to_s]
end
def initialize
@columns = {}
end
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 do |row|
csv_row = CsvRow.new
row.each_index {|column_idx| csv_row.columns[@headers[column_idx]] = row[column_idx]}
yield csv_row
end
end
attr_accessor :headers, :csv_contents
def initialize
read
end
end
end
class RubyCsv
include ActsAsCsv
acts_as_csv
end
csv = RubyCsv.new
csv.each {|row| puts row.brand}
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
(0..3).each {|iteration| p a[(iteration*4)..(iteration*4 + 3)]}
a.each_slice(4) {|content| p content}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment