我正在编写Ruby脚本,并希望使用n-ary树数据结构.
是否有一个很好的实现可用作源代码?谢谢.
为了扩展Otto的答案,让Hash自动生成数组的一种简单方法是使用默认值块Hash::new
,如下所示:
node_children = Hash.new { |_node_children, node_key| _node_children[node_key] = [] }
但实际上,代码取决于您想要对阵列执行的操作.您可以使用Hashes和Arrays设置它们,也可以创建一些类:
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
例如,此代码提供:
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
一个哈希,其属性都是数组?