Skip to content

Instantly share code, notes, and snippets.

@mruoss
Created August 13, 2011 15:29
Show Gist options
  • Save mruoss/1143955 to your computer and use it in GitHub Desktop.
Save mruoss/1143955 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby
#!/usr/bin/env ruby
# print array in slices using each
a = (1..16).to_a
(0..3).each do |i|
p a[4*i..4*i+3]
end
# print array in slices using each_slice
a.each_slice(4) {|s| p s}
############################
# Tree initialized by a hash
############################
class Tree
attr_accessor :children, :node_name
def initialize(tree, node_name=nil)
if (node_name.nil? and tree.size == 1)
first = tree.first
@node_name = first[0]
children_hash = first[1]
elsif (not node_name.nil?)
@node_name = node_name
children_hash = tree
else
raise ArgumentError
end
@children = children_hash.collect {|name, subtree| Tree.new(subtree, name)}
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
my_tree = Tree.new({
'grandpa' => {
'dad' => {
'child 1' => {}, 'child 2' => {}
},
'uncle' => {
'child 3' => {}, 'child 4' => {}
}
}
})
my_tree.visit_all {|node| puts node.node_name}
#!/usr/bin/env ruby
filename = ARGV[0]
phrase = ARGV[1]
if (filename.nil? || phrase.nil?)
puts "Usage: day2_grep.rb filename phrase"
exit;
end
File.open(filename, File::RDONLY) do |file|
file.each_with_index { |line, nr| puts "Line " + (nr+1).to_s.rjust(4) + ": " + line if line =~ /#{phrase}/ }
end
class CsvRow
def initialize(headers, row)
@headers = headers
@row = row
end
def method_missing(name, *args)
idx = headers.index(name.to_s)
raise NoMethodError if idx.nil?
row[idx]
end
def headers
@headers
end
def row
@row
end
end
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
define_method 'read' do
file = File.new(self.class.to_s.downcase + '.txt')
@headers = file.gets.chomp.split(', ')
file.each do |row|
@result << row.chomp.split(', ')
end
end
define_method "headers" do
@headers
end
define_method "csv_contents" do
@result
end
define_method "initialize" do
@result = []
read
end
define_method "each" do |*args, &block|
csv_contents.each {|row| block.call CsvRow.new(headers, row)}
end
end
end
class RubyCsv
include ActsAsCsv
acts_as_csv
end
m = RubyCsv.new
m.each {|row| puts row.header1}
# rubycsv.txt:
# header1, header2
# row1_col1, row1_col2
# row2_col1, row2_col2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment