tree.rb

version 0.1 - Aug.24.2000
version 0.2 - Aug.25.2000

目的

ツリー構造のデータを扱うためのライブラリです。
テキストでツリーの表示もできます。

メソッド

<<
ツリーに親子関係を追加します。
Arrayで渡して下さい。

to_s(表示する最大レベル, フォーマット, インデント)
文字列として表示します。
表示する最大レベルを数字で指定することで枝を省略することができます。
フォーマット、インデントを変えることで表示が変えられます。
デフォルトは"%s+- %s\n"と" "です。
最初の%sがインデントで次の%sが要素名です。
使用例はソースを見て下さい。

roots
トップレベルの要素をArrayで返します。

sibling(item)
itemと同レベルの要素をArrayで返します。

include?(item)
itemを要素として含むかどうかを返します。

is_brother?(one, another) / is_sister?(one, another)
oneがanotherと同レベルかどうかを返します。

depth(item)
itemのツリーのトップからの距離を返します。

is_descendant?(one, another)
oneがanotherの子孫かどうかを返します。

is_ancestor?(one, another)
oneがanotherの先祖かどうかを返します。

relationship(one, another)
oneのanotherにとっての関係を文字列で返します。
返す値は、"brother or sister", "ancestor", "descendant", "unknown relation"のいずれかです。

children(item)
itemの直接の子供の要素を配列として返します。

parents(item)
itemの直接の親の要素を配列として返します。

バグ

配列内に配列があるものの使用は想定していません。
追加に関して順序は保存されません。

使用例

require 'tree'

tree = Tree.new
tree << [1, 2, 3, 4]
tree << [2, 5, 6]
tree << [3, 7, 8]
print tree
print "parents of 1 are ", tree.parents(1).join(", "), "\n"
print "parents of 2 are ", tree.parents(2).join(", "), "\n"
print "children of 2 are ", tree.children(2).join(", "), "\n"
print "children of 8 are ", tree.children(8).join(", "), "\n"
print "3 is ", tree.relationship(3, 5), " of 5\n"
print "2 is ", tree.relationship(2, 8), " of 8\n"
print "8 is ", tree.relationship(8, 2), " of 2\n"
print "4 is ", tree.relationship(4, 6), " of 6\n"

--- 結果
+- 1
  +- 2
    +- 3
      +- 4
      +- 7
        +- 8
    +- 5
      +- 6
parents of 1 are
parents of 2 are 1
children of 2 are 3, 5
children of 8 are
3 is brother or sister of 5
2 is ancestor of 8
8 is descendant of 2
4 is unknown relation of 6
print tree
---
tree.rbもrubyのメソッドツリーの使用例になっています。

if __FILE__ == $0
  tree = Tree.new
  Module.constants.sort.each do |x|
    eval <<-EOT
      if #{x}.is_a?(Class) then
        tree << #{x}.ancestors.reverse
      end
    EOT
  end
  print tree.to_s(3)
  print tree

  p tree.sibling(Array)
  tree.sibling(Array).each do |x|
    p x
  end
end
download

back