Class: Spacetree::Node

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/spacetree/node.rb

Overview

Represent a node respectively a tree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = nil, *children) ⇒ Node

Returns a new instance of Node.

Parameters:

  • value (defaults to: nil)

    value of the 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

#childrenObject

Returns the value of attribute children.



9
10
11
# File 'lib/spacetree/node.rb', line 9

def children
  @children
end

#valueObject

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

Parameters:

  • indent (defaults to: 2)

    Count of spaces to indent a level deeper

  • level (defaults to: 0)

    level of indentation



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_sObject



53
54
55
# File 'lib/spacetree/node.rb', line 53

def to_s
  emit
end