Skip to content

Instantly share code, notes, and snippets.

@ponkore
Created April 11, 2012 12:23
Show Gist options
  • Save ponkore/2359026 to your computer and use it in GitHub Desktop.
Save ponkore/2359026 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Ruby 2nd)
#!/usr/bin/env ruby
arr = (1..16).to_a
tmp = []
arr.each do |val|
tmp.push(val)
if tmp.length == 4
puts tmp.join(",")
tmp = []
end
end
bash$ ./b.rb
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
bash$
#!/usr/bin/env ruby
arr = (1..16).to_a
arr.each_slice(4) do |val|
puts val.join(",")
end
bash$ ./c.rb
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
bash$
#!/usr/bin/env ruby
tree_data = {
'grandpa' => {
'dad' => {
'child 1'=>[],
'child 2'=>[]
},
'uncle' => {
'child 3'=>[],
'child 4'=>[]
}
}
}
class Tree
attr_reader :children, :node_name
# あえてデバッグ用出力を残してみた
def initialize(tree)
puts "---"
p tree
tree = tree.to_a[0] if tree.is_a?(Hash)
p tree[0]
@node_name = tree[0]
@children = []
tree[1].each do |subtree|
p subtree
@children.push(Tree.new(subtree))
end
puts "---"
end
def visit_all(&block)
visit &block
@children.each {|c| c.visit_all &block }
end
def visit(&block)
block.call self
end
end
all_tree = Tree.new(tree_data)
all_tree.visit_all do |tree|
puts "#{tree.node_name} has children(#{tree.children.size})"
end
bash$ ./d.rb
---
{"grandpa"=>{"dad"=>{"child 1"=>[], "child 2"=>[]}, "uncle"=>{"child 3"=>[], "child 4"=>[]}}}
"grandpa"
["dad", {"child 1"=>[], "child 2"=>[]}]
---
["dad", {"child 1"=>[], "child 2"=>[]}]
"dad"
["child 1", []]
---
["child 1", []]
"child 1"
---
["child 2", []]
---
["child 2", []]
"child 2"
---
---
["uncle", {"child 3"=>[], "child 4"=>[]}]
---
["uncle", {"child 3"=>[], "child 4"=>[]}]
"uncle"
["child 3", []]
---
["child 3", []]
"child 3"
---
["child 4", []]
---
["child 4", []]
"child 4"
---
---
---
grandpa has children(2)
dad has children(2)
child 1 has children(0)
child 2 has children(0)
uncle has children(2)
child 3 has children(0)
child 4 has children(0)
#<Tree:0x007fa2bb906ce8 @node_name="grandpa", @children=[#<Tree:0x007fa2bb9067e8 @node_name="dad", @children=[#<Tree:0x007fa2bb906590 @node_name="child 1", @children=[]>, #<Tree:0x007fa2bb9063b0 @node_name="child 2", @children=[]>]>, #<Tree:0x007fa2bb906108 @node_name="uncle", @children=[#<Tree:0x007fa2bb905eb0 @node_name="child 3", @children=[]>, #<Tree:0x007fa2bb905cd0 @node_name="child 4", @children=[]>]>]>
bash$
#!/usr/bin/env ruby
re = Regexp.compile(ARGV[0])
File.open(ARGV[1]) do |infile|
infile.each_with_index do |line, i|
puts "#{i}: #{line}" if re =~ line
end
end
bash$ ./e.rb f ./e.rb
3: File.open(ARGV[1]) do |infile|
4: infile.each_with_index do |line, i|
5: puts "#{i}: #{line}" if re =~ line
bash$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment