開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Ruby 2.3 (プログラミング言語)
7つの言語 7つの世界 (Bruce A. Tate (著)、まつもとゆきひろ (監訳)、田和 勝 (翻訳)、オーム社)の第2章(Ruby)、2.3(2日目: 空からふわふわ舞い降りる)、セルフスタディ2日目を取り組んでみる。
セルフスタディ2日目
コード(Emacs)
#!/usr/bin/env ruby2.3
# -*- coding: utf-8 -*-
a1 = (1..16).to_a
a2 = (1..4).to_a
(a1 + a2).each do |i|
puts i
end
class Tree
attr_accessor :children, :node_name
def initialize(tree)
@node_name = tree.keys[0]
@children = tree.values[0]
end
def visit_all(&block)
visit &block
children.each do |k, v|
if v.class == Array
puts k
else
Tree.new({k => v}).visit_all &block
end
end
end
def visit(&block)
block.call self
end
end
tree = Tree.new({'grandpa' => {'dad' => {'child 1' => [],
'child 2' => []},
'uncle' => {'child 3' => [],
'child 4' => []}}})
puts "Visiting a node"
tree.visit do |node|
puts node.node_name
end
puts
puts "visiting entire tree"
tree.visit_all do |node|
puts node.node_name
end
puts
i = 1
File.open('sample.rb').each do |line|
print "#{i}: #{line}" if line.match "end"
i += 1
end
入出力結果(Terminal, irb)
$ ./sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
4
Visiting a node
grandpa
visiting entire tree
grandpa
dad
child 1
child 2
uncle
child 3
child 4
9: end
17: end
26: end
27: end
28: end
32: end
33: end
43: end
49: end
54: print "#{i}: #{line}" if line.match "end"
56: end
$
0 コメント:
コメントを投稿