[LRUG] Pruning a tree

Andrew Stewart boss at airbladesoftware.com
Tue Jun 28 03:16:43 PDT 2011


On 28 Jun 2011, at 10:31, Tom Stuart wrote:
>>> tree = Node.new(2, [Node.new(3, [Node.new(4, [Node.new(5)])]), Node.new(6)])
>>> tree.to_s
> => "2 -> [3 -> [4 -> [5]], 6]"
>>> tree.filter(&:even?).to_s
> => "2 -> [3 -> [4], 6]"
>>> tree.filter(&:odd?).to_s
> => "2 -> [3 -> [4 -> [5]]]"

Nifty.

I have also got the nested hashes working:

  def rmerge(ha, hb)
    ha.merge(hb) do |k, va, vb|
      if va.is_a?(Hash) && vb.is_a?(Hash)
        rmerge(va, vb)
      elsif va.is_a?(Array) && vb.is_a?(Hash) && (elem = va.detect{|e| e.is_a?(Hash) && e.keys.first == vb.keys.first})
        index = va.index elem
        va[index] = rmerge va[index], vb
        va
      else
        [va, vb]
      end
    end
  end

  def array_to_nested_hashes(ary)
    ary.reverse.inject { |a,n| { n => a } }
  end

  nodes_to_keep = [node_m, node_x, ...]

  nodes_to_keep.inject({}) do |tree, node|
    t = array_to_nested_hashes node.ancestors.reverse
    rmerge(tree, t)
  end

Thanks everyone!

Yours,
Andy

-------
http://airbladesoftware.com



More information about the Chat mailing list