What is RubyTree?

RubyTree is a simple and general purpose implementation of the Tree data structure for the Ruby language. RubyTree provides a clean, node-based model for building hierarchical structures (menus, file systems, org charts, parse trees) with predictable traversal and modification APIs. The library emphasizes clarity and correctness, while staying flexible enough to adapt to specialized tree variants in your own code.

Use RubyTree when you need explicit parent/child relationships, named nodes, or a simple way to walk and transform hierarchies. The core API is intentionally small, and the library is designed to be easy to read and extend.

The current version provides implementations of:

  • A general purpose node-based tree data structure, and
  • A binary tree.

RubyTree is available as a rubygem and is released under the BSD License.

What's New? R2.2.0 release

Version 2.2.0 released on February 6, 2026.

  • Prevent cycles by rejecting attempts to add an ancestor as a child.
  • Ensure remove_all! detaches children by clearing their parent links.
  • Raise on sibling name collisions in rename_child.
  • Harden binary tree child assignment (set_child_at) with proper index errors and cleanup of parent/hash references.
  • Make traversals resilient to missing children by skipping nil nodes in postordered_each and breadth_each.
  • Return a level-wise enumerator from each_level when no block is given.
  • Improve to_s formatting to show <Empty> for nil content.

Upgrade notes for 2.2.0:

  • Cycle prevention now raises when adding an ancestor as a child.
  • rename_child now raises on sibling name collisions.
  • set_child_at now raises for invalid indexes.
See the the Changelog for details.

Getting Started

Installing RubyTree

Download & install the latest version using rubygem (you may need to do this with admin rights):

$ gem install rubytree -v 2.2.0
$ gem update rubytree

Check the documentation for RubyTree by looking up the RDoc using ri, or by browsing the online documentation.

$ ri Tree::TreeNode

Quick Start

root = Tree::TreeNode.new("root", "Root")
root << Tree::TreeNode.new("child", "Child")
root.each { |node| puts node.name }

FAQ

Q: What is RubyTree?

A: RubyTree is a Ruby implementation of a generic tree data structure with named nodes, traversal helpers, and a binary tree variant.

Q: Does RubyTree support JSON or marshaling?

A: Yes. RubyTree can import from and export to JSON and supports Ruby object marshaling.

Q: What is the primary class?

A: The primary class is Tree::TreeNode.

Q: What Ruby versions are supported?

A: Ruby 2.7+ (current release).

Support & Security

Supported versions: the latest release (2.2.0). Older releases are best-effort. For support, please use the GitHub issue tracker.

Contributing to RubyTree

Help RubyTree with your suggestions, bug reports, or patches and pull requests.