Class: Hash::As::Tree::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/hash/as/tree.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value: nil, key: nil, parent: nil) ⇒ Node

Returns a new instance of Node.



44
45
46
# File 'lib/hash/as/tree.rb', line 44

def initialize value: nil, key: nil, parent: nil
  @value, @key, @parent = value, key, parent
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



47
48
49
# File 'lib/hash/as/tree.rb', line 47

def key
  @key
end

#parentObject

Returns the value of attribute parent.



47
48
49
# File 'lib/hash/as/tree.rb', line 47

def parent
  @parent
end

#valueObject

Returns the value of attribute value.



47
48
49
# File 'lib/hash/as/tree.rb', line 47

def value
  @value
end

Instance Method Details

#childrenObject



68
69
70
71
72
73
74
75
76
# File 'lib/hash/as/tree.rb', line 68

def children
  if value.is_a? Hash
    value.map do |key, value|
      Node.new value: value, key: key, parent: self
    end
  else
    []
  end
end

#to_aObject



78
79
80
# File 'lib/hash/as/tree.rb', line 78

def to_a
  [key, value]
end

#to_hObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/hash/as/tree.rb', line 49

def to_h
  if key
    if value.is_a?(Hash) && (not value.empty?)
      { key => children.map(&:to_h).reduce(&:merge) }
    else
      { key => value }
    end
  else
    children.map(&:to_h).reduce(&:merge)
  end
end

#with(**kwargs) ⇒ Object



61
62
63
64
65
66
# File 'lib/hash/as/tree.rb', line 61

def with **kwargs
  Node.new \
    value:  (kwargs[:value] or value),
    key:    (kwargs[:key] or key),
    parent: (kwargs[:parent] or parent)
end