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}
class Thing
def deep_each
yield self
@contents.deep_each { |t| yield t }
end
end
I have a Class whose instances should contain more instances of the Class.
Iterating through the contents of one instance is simple.
The following works just fine.
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?