From: John Winters Date: 2008-08-01T06:17:40+09:00 Subject: Re: Needing help with which to_s gets called Thanks to all for some very useful pointers. On Thu, Jul 31, 2008 at 4:41 PM, Sebastian Hungerecker wrote: [snip] > You're right. join special cases arrays as well, joining nested arrays as well > instead of to_sing them (that or it just calls flatten on the array before > starting it's work). That certainly seems to be the case, as witnessed by the following snippet. a = ["a", "b", "c"] b = ["d", "e", "f"] c = Array.new c << a c << b puts "Size of c is #{c.size}" puts c.join(", ") which produces: Size of c is 2 a, b, c, d, e, f It looks very much like join will flatten anything which it thinks it can. Gregory Brown wrote: > > I guess this is an example of core class special cases that I was > worried about in an earlier thread today. > > I really don't think it's a good practice to subclass core classes > unless you are only adding new behaviour. > Wrapping and delegating is much more predictable. Thank you - I'll take note of that. My original problem was that I have a structure involving nested arrays and I wanted them to print out with the nesting apparent. Sub-classing Array seemed the obvious way to do it, but perhaps not. > That having been said, the problem goes away if you first explicitly > map using to_s before the join(), but this is an indication of the > kind of hacks subclassing core objects like Array will force upon you > :-/ > > > def to_s > "[Baker: #{@contents.map { |e| e.to_s }.join(", ")}]" > end Adding to the snippet above: puts c.map { |e| e.to_s }.join(", ") Produces: abc, def So I now have a choice of two ways to do it. Cheers, John -- Posted via http://www.ruby-forum.com/.