Skip to content

Instantly share code, notes, and snippets.

@knewter
Created February 24, 2013 21:12
Show Gist options
  • Save knewter/5025642 to your computer and use it in GitHub Desktop.
Save knewter/5025642 to your computer and use it in GitHub Desktop.
Just toying with some trees / repository fun
# So say you want to deal with a tree structure in ruby
tree_data = [
{ name: 'root', childen: [
{ name: 'first' },
{ name: 'second' }
]
]
# That pretty much covers it. I would expect you'd want it to be wrapped in some kind of helper class
# for accessing it in a more pleasant way, so...
class Tree
attr_reader :data
def initialize(data)
@data = data
end
def root
Node.new(data[0], self, nil)
end
class Node
attr_reader :data, :tree, :parent
def initialize(data, tree, parent)
@data = data
@tree = tree
@parent = parent
end
def children
data[:children].map{|c| Node.new(c, tree, self) }
end
def siblings
parent ? parent.children : []
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment