Class: Node

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

Constant Summary collapse

INVALID_WORD_MSG =
"\e[31m%s does not exist in tree\e[0m".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root = false) ⇒ Node

Returns a new instance of Node.



12
13
14
15
16
17
18
19
# File 'lib/node.rb', line 12

def initialize(root = false)
  @char    = nil
  @is_end  = false
  @roots   = []
  @is_root = root
  @count   = 1
  @tree    = []
end

Instance Attribute Details

#charObject

Returns the value of attribute char.



7
8
9
# File 'lib/node.rb', line 7

def char
  @char
end

#countObject (readonly)

Returns the value of attribute count.



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

def count
  @count
end

#is_endObject

Returns the value of attribute is_end.



7
8
9
# File 'lib/node.rb', line 7

def is_end
  @is_end
end

#is_rootObject

Returns the value of attribute is_root.



7
8
9
# File 'lib/node.rb', line 7

def is_root
  @is_root
end

#rootsObject

Returns the value of attribute roots.



7
8
9
# File 'lib/node.rb', line 7

def roots
  @roots
end

Instance Method Details

#add(word) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/node.rb', line 21

def add(word)
  return false unless validate_word(word)

  have = have_in_childs(word)
  if have.empty?
    no_child_found(word)
  else
    child_found(have, word)
  end
  true
end

#delete(word) ⇒ Object



55
56
57
# File 'lib/node.rb', line 55

def delete(word)
  validate_before_delete(word) ? do_delete(word) : invalid_delete(word)
end

#find(string) ⇒ Object



59
60
61
# File 'lib/node.rb', line 59

def find(string)
  include?(string, true)
end

#include?(word, is_word = false) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/node.rb', line 33

def include?(word, is_word = false)
  str = ''
  obj = self

  word.chars.each do |chr|
    return false if obj.nil?

    obj = obj.roots.select { |item| item.to_s == chr }.first
    str += obj.to_s
  end
  is_word ? (str == word && obj.is_end == true) : str == word
end

#increase_countObject



67
68
69
# File 'lib/node.rb', line 67

def increase_count
  @count += 1
end

#list(word = '') ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/node.rb', line 46

def list(word = '')
  tree = @tree
  where = word.empty? ? self : have_in_childs(word)[0]
  recursive_list(where, word)
  @tree = []

  tree.sort_by { |s| s.scan(/\d+/).first.to_i }
end

#to_sObject



63
64
65
# File 'lib/node.rb', line 63

def to_s
  @char
end