Class: Spacetree::Node
- Inherits:
-
Object
- Object
- Spacetree::Node
- Includes:
- Enumerable
- Defined in:
- lib/spacetree/node.rb
Overview
Represent a node respectively a tree
Instance Attribute Summary collapse
-
#children ⇒ Object
Returns the value of attribute children.
-
#value ⇒ Object
Returns the value of attribute value.
Instance Method Summary collapse
- #==(o) ⇒ Object
- #each(*args, &blk) ⇒ Object
-
#emit(indent: 2, level: 0) ⇒ Object
Generate a formatted string representation of a node and its children recursively.
-
#initialize(value = nil, *children) ⇒ Node
constructor
A new instance of Node.
- #to_s ⇒ Object
Constructor Details
#initialize(value = nil, *children) ⇒ Node
Returns a new instance of Node.
13 14 15 16 |
# File 'lib/spacetree/node.rb', line 13 def initialize value=nil, *children @value = value @children = children end |
Instance Attribute Details
#children ⇒ Object
Returns the value of attribute children.
9 10 11 |
# File 'lib/spacetree/node.rb', line 9 def children @children end |
#value ⇒ Object
Returns the value of attribute value.
9 10 11 |
# File 'lib/spacetree/node.rb', line 9 def value @value end |
Instance Method Details
#==(o) ⇒ Object
18 19 20 21 |
# File 'lib/spacetree/node.rb', line 18 def == o return false unless o.kind_of? Node [self.value, self.children] == [o.value, o.children] end |
#each(*args, &blk) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/spacetree/node.rb', line 23 def each *args, &blk enum = Enumerator.new do |y| y << self children.each do |c| c.each *args, &blk end end if block_given? enum.each *args, &blk else enum end end |
#emit(indent: 2, level: 0) ⇒ Object
Generate a formatted string representation of a node and its children recursively
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/spacetree/node.rb', line 41 def emit indent: 2, level: 0 res = [] if value.nil? children.each {|c| res << c.emit(indent: indent, level: level)} else spaces = ' ' * indent * level res << (spaces << value.to_s) children.each {|c| res << c.emit(indent: indent, level: level+1)} end res.join("\n") end |
#to_s ⇒ Object
53 54 55 |
# File 'lib/spacetree/node.rb', line 53 def to_s emit end |