Skip to content

Instantly share code, notes, and snippets.

@judy2k
Created November 2, 2011 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judy2k/1333973 to your computer and use it in GitHub Desktop.
Save judy2k/1333973 to your computer and use it in GitHub Desktop.
Ruby
module ActsAsCsv
class Row < Array
def initialize(ary, headings)
super(ary)
@headings = headings
end
def method_missing(name, *args)
idx = @headings.index name.to_s
self[idx] if idx != nil
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
attr_accessor :headers, :csv_contents
def initialize
read
end
def each(&block)
csv_contents.each do |row|
block.call Row.new(row, @headers)
end
end
end
class RubyCsv # no inheritance! You can mix it in
include ActsAsCsv
end
m = RubyCsv.new
puts m.headers.inspect
puts m.csv_contents.inspect
m.each do |row|
print row.one, row.two
print row.three
end
num = rand 10
while true
print "Guess the number: "
guess = gets.to_i
if guess < num
print "Too low!\n"
elsif guess > num
print "Too high!\n"
else
print "Yay! You got it right!\n"
break
end
end
def grep(fn, re)
File.open(fn) do |f|
f.each do |l|
print "#{f.lineno}: #{l}" if re.match l
end
end
end
grep('day2_grep.rb', /do/)
class Tree
attr_accessor :name, :children
def initialize(hier)
hier.each do |k, v|
@name = k
@children = v.map do |ch, desc|
Tree.new(ch => desc)
end
end
end
def visit_one(&block)
block.call self
end
def visit(&block)
visit_one &block
children.each do |c|
c.visit &block
end
end
end
tree = Tree.new('grandpa' => {
'dad' => {'child 1' => {}, 'child 2' => {} },
'uncle' => {'child 3' => {}, 'child 4' => {} }
})
tree.visit do |node|
p node.name
end
@mukolweke
Copy link

whats the number going to be in ruby_day1.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment