Class: BasicTree
Constant Summary collapse
- VERSION =
"1.0.0"
Instance Attribute Summary collapse
-
#object ⇒ Object
Returns the value of attribute object.
-
#parent ⇒ Object
Returns the value of attribute parent.
Instance Method Summary collapse
- #add(object, &block) ⇒ Object
- #ancestors ⇒ Object
- #children ⇒ Object
- #descendants ⇒ Object
-
#initialize(object, parent = nil, &block) ⇒ BasicTree
constructor
A new instance of BasicTree.
- #leaf? ⇒ Boolean
- #level ⇒ Object
- #path ⇒ Object
- #root ⇒ Object
- #root? ⇒ Boolean
- #siblings ⇒ Object
- #subtree ⇒ Object
Constructor Details
#initialize(object, parent = nil, &block) ⇒ BasicTree
Returns a new instance of BasicTree.
7 8 9 10 11 12 13 14 |
# File 'lib/basic_tree.rb', line 7 def initialize(object, parent = nil, &block) self.object = object if parent self.parent = parent parent.children << self end instance_eval(&block) if block_given? end |
Instance Attribute Details
#object ⇒ Object
Returns the value of attribute object.
16 17 18 |
# File 'lib/basic_tree.rb', line 16 def object @object end |
#parent ⇒ Object
Returns the value of attribute parent.
16 17 18 |
# File 'lib/basic_tree.rb', line 16 def parent @parent end |
Instance Method Details
#add(object, &block) ⇒ Object
18 19 20 |
# File 'lib/basic_tree.rb', line 18 def add(object, &block) self.class.new(object, self, &block) end |
#ancestors ⇒ Object
26 27 28 |
# File 'lib/basic_tree.rb', line 26 def ancestors root? ? [] : (parent.ancestors << parent) end |
#children ⇒ Object
58 59 60 |
# File 'lib/basic_tree.rb', line 58 def children @children ||= [] end |
#descendants ⇒ Object
30 31 32 |
# File 'lib/basic_tree.rb', line 30 def descendants children.map { |c| [c] + c.descendants }.flatten end |
#leaf? ⇒ Boolean
54 55 56 |
# File 'lib/basic_tree.rb', line 54 def leaf? children.empty? end |
#level ⇒ Object
46 47 48 |
# File 'lib/basic_tree.rb', line 46 def level path.size end |
#path ⇒ Object
22 23 24 |
# File 'lib/basic_tree.rb', line 22 def path ancestors << self end |
#root ⇒ Object
42 43 44 |
# File 'lib/basic_tree.rb', line 42 def root path.first end |
#root? ⇒ Boolean
50 51 52 |
# File 'lib/basic_tree.rb', line 50 def root? !parent end |
#siblings ⇒ Object
38 39 40 |
# File 'lib/basic_tree.rb', line 38 def siblings root? ? [] : parent.children.select { |child| child != self } end |
#subtree ⇒ Object
34 35 36 |
# File 'lib/basic_tree.rb', line 34 def subtree [self] + descendants end |