罫線を使ったツリーを書く為のユーティリティ
微妙に汎用的に使える(かもしれない)、罫線を使ったツリーを書く為のユーティリティができあがったので公開。実装とサンプルは以下です。
#罫線を使ったツリーを書く為のユーティリティ class Node def initialize( name ) @name = name @children = [] yield self if block_given? end # 子ノードを追加する。 def <<(child) @children << child self end def to_s( indent="" ) str = indent.dup str << name.to_s << "\n" child_indent = indent.gsub(/├/, "│").gsub(/└/, " ") @children.each_index {|i| tmp = child_indent + ( i >= children.length-1 ? "└" : "├" ) str << children[i].to_s( tmp ) } return str end attr :name, true attr :children, true end # ツリーを構築 root = Node.new("root") {|r| r << Node.new("aa") {|a| a << Node.new("cc") a << Node.new("dd") } r << Node.new("bb") } # 描画 puts root.to_s
実行結果です。
root ├aa │├cc │└dd └bb