Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active January 27, 2022 15:11

Revisions

  1. JoelQ revised this gist Jan 27, 2022. No changes.
  2. JoelQ created this gist Jan 27, 2022.
    42 changes: 42 additions & 0 deletions tree.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    class Tree
    attr_reader :value, :left, :right

    def initialize(value, left, right)
    @value = value
    @left = left
    @right = right
    end

    def reduce(initial, &block)
    left_acc = left.reduce(initial, &block)
    right_acc = right.reduce(initial, &block)

    block.call(value, left_acc, right_acc)
    end

    def inspect
    reduce("leaf") { |val, l, r| "#{val} (#{l}, #{r})" }
    end
    end

    class Leaf
    def reduce(initial, &block)
    initial
    end
    end


    # This section makes it easy to load up a tree in a console and experiment on it
    # Run the script with `ruby tree.rb`

    tree = Tree.new(
    5,
    Tree.new(4, Leaf.new, Leaf.new),
    Tree.new(
    3,
    Tree.new(2, Leaf.new, Leaf.new),
    Leaf.new
    )
    )

    binding.irb