C
Colin Bartlett
The more OOP approach would be:
=A0 class Object
=A0 =A0 def visits
=A0 =A0 =A0 yield(self)
=A0 =A0 end
=A0 end
=A0 module Enumerable
=A0 =A0 def visits(&block)
=A0 =A0 =A0 each{ |item| item.visits(&block) }
=A0 =A0 end
=A0 end
This won't behave well if passed a true graph (not just tree or dag)
of ruby objects. For instance:
=A0a=3D[]
=A0a<<a
=A0a.visits{|x| p x }
At one time, I got interested enough in this problem to write a fairly
complete solution to this problem (at least I think so). If
interested, please have a look at:
=A0http://github.com/coatl/ron/blob/master/lib/ron/graphedge.rb
So, temporarily ignoring the problem of possible infinite loops
(which I'd just begun to worry about - I was using a =3D [2] ; a << a,
which in IRB gives [2, [...]], and a =3D a[1] #=3D> [2, [...]],
but your example is even simpler)
you opted for recursive_each (and recursive_reverse_each)?
Going back to the original problem, my understanding is that
Roger Pack was looking for a simple way of putting some
data into an array and then getting at it, in which case
the likely maximum depth may well be known, and then
Robert Klemme's solution with a mandatory level/depth argument
seems to work.
So I withdraw my suggestion of level/depth =3D nil for infinite depth!
(Interestingly, Numeric#step raises an error if the step is 0,
but Date#step seems to allow infinite loops with a step of 0.)