From: Eric Mahurin Date: 2005-10-27T23:38:28+09:00 Subject: Re: overriding #inspect --- Robert Klemme wrote: > Eric Mahurin wrote: > > --- Robert Klemme wrote: > > > >>>>>> On 10/26/05, Eric Mahurin > >> wrote: > >>>>>>> Anybody know what the best way to override inspect > where you > >>>>>>> may have a recursive data structure? > > > > > >> .... which reminds me of an RCR I've been wanting to > submit > >> for quite some > >> time now: > >> http://rcrchive.net/rcr/show/323 > >> > >> This could help here, too. > >> > >> Kind regards > >> > >> robert > > > > Could you describe how this could be used to override > #inspect? > > Or any other example? I think a ruby implementation RCR > would > > go a long way. > > Without going into the details: > > def inspect > s = "" > traverse(self) do |obj| > s << "(" if Enumerable === obj > s << do_whatever(obj) > s << ")" if Enumerable === obj > end > s > end > > It might even be interesting to have a second parameter which > indicates > the distance from the start object. That way indentation > would be easy > and maybe it can be used for other stuff as well. Just an > idea. But this wouldn't allow child objects to use their own #inspect, would it? I think the best solution for changing the #inspect behavior of a class would be to have #inspect deal with recursion issues and call another method (or two) to generate the strings: def inspect # several ways to accomplish this thread-local instance var if inspect_thread_local_instance_variable inspect_stop else begin inspect_thread_local_instance_variable = true inspect_contents ensure inspect_thread_local_instance_variable = false end end def inspect_stop .. generate an inspect string w/o children ("..." instead) end def inspect_children .. generate an inspect string w/ children end With this infrastructure, you could easily change the #inspect behavior by overriding #inspect_stop and/or #inspect_children. No need to worry about recursion. __________________________________ Yahoo! FareChase: Search multiple travel sites in one click. http://farechase.yahoo.com