28 Mar, 2011, Chris Bailey wrote in the 1st comment:
Votes: 0
I might be over thinking this, but I cannot figure it out for the life of me! =P

I have a Class whose instances should contain more instances of the Class.

class Thing

def initialize(name=nil)
@name = name
@contents = []
end

def name
@name
end

def add_thing(thing)
@contents.push thing
end

end


Iterating through the contents of one instance is simple.

class Thing
def each
@contents.each {|t| yield t}
end
end


The following works just fine.

thing = Thing.new('Box')
thing.add_thing(Thing.new('Horse'))
thing.add_thing(Thing.new('Cat'))
thing.each {|t| puts t.name}


What I would like to be able to do is pass a block to be executed on an instance, all instances it contains, and all that they contain, and so on. I was thinking that I could just traverse the children one at a time until I come to an instance that has no children (@contents). Then head back to the deepest node (thing?) that has unvisted children and continue from there. I have tried to do that in a few different ways, none worked. What gives?
28 Mar, 2011, Runter wrote in the 2nd comment:
Votes: 0
class Thing < Array
def each (&blk)
super do |thing|
yield thing
thing.each &blk if thing.is_a?(Thing)
end
end
end

thing = Thing.new
thing << "roar" << "roar2" # it contains some roars.
thing << (Thing.new << "mew" << "mew2") # it contains a thing contain mews

thing.each {|thing| puts thing}
28 Mar, 2011, kiasyn wrote in the 3rd comment:
Votes: 0
would you not just do:

class Thing
def deep_each
yield self
@contents.deep_each { |t| yield t }
end
end
29 Mar, 2011, Chris Bailey wrote in the 4th comment:
Votes: 0
Kia - That only goes one level deep I believe.

Runter - Seems to be working, lack of sleep must have made me sofa king we todd it? =)
29 Mar, 2011, kiasyn wrote in the 5th comment:
Votes: 0
Chris Bailey said:
Kia - That only goes one level deep I believe.

Runter - Seems to be working, lack of sleep must have made me sofa king we todd it? =)


yeah i kind of forgot what i was writing half way through writing it :P
29 Mar, 2011, David Haley wrote in the 6th comment:
Votes: 0
This is just classic tree traversal, correct…?
29 Mar, 2011, Chris Bailey wrote in the 7th comment:
Votes: 0
Yeah, I guess so. I don't know why I was having such a hard time wrapping my head around it. For some reason I thought it had to be different to allow for such a variable amount of children.
0.0/7