Ruby way to create an n-ary tree

I am writing a Ruby script and would like to use the n-ary tree data structure.

Is there a good implementation available as source code? Thanks.

+3
source share
3 answers

To expand on Otto's answer, an easy way to get Hash arrays for automatic revitalization is to use a block of default values ​​with Hash::new, for example:

node_children = Hash.new { |_node_children, node_key| _node_children[node_key] = [] }

But really, the code depends on what you want to do with your arrays. You can also configure them using hashes and arrays or make several classes:

class Node
    attr_accessor :value, :children
    def initialize(value, children=[])
        @value = value
        @children = children
    end
    def to_s(indent=0)
        value_s = @value.to_s
        sub_indent = indent + value_s.length
        value_s + @children.map { |child| " - " + child.to_s(sub_indent + 3) }.join("\n" + ' ' * sub_indent)
    end
end

ROOT = Node.new('root', %w{ farleft left center right farright }.map { |str| Node.new(str) } )
puts "Original Tree"
puts ROOT
puts

ROOT.children.each do |node| 
    node.children = %w{ one two three four }.map { |str| Node.new(node.value + ':' + str) }
end
puts "New Tree"
puts ROOT
puts

This code, for example, gives:

Original Tree
root - farleft
     - left
     - center
     - right
     - farright

New Tree
root - farleft - farleft:one
               - farleft:two
               - farleft:three
               - farleft:four
     - left - left:one
            - left:two
            - left:three
            - left:four
     - center - center:one
              - center:two
              - center:three
              - center:four
     - right - right:one
             - right:two
             - right:three
             - right:four
     - farright - farright:one
                - farright:two
                - farright:three
                - farright:four
+11
source

A hash whose attributes are all arrays?

+5

RubyTree gem .

+2

Source: https://habr.com/ru/post/1702553/


All Articles