Created
February 24, 2013 21:12
-
-
Save knewter/5025642 to your computer and use it in GitHub Desktop.
Just toying with some trees / repository fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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