From: Dick Davies Date: 2004-04-24T19:39:09+09:00 Subject: Re: Problem assigning an Array object to an Array-subclass object * Kristof Bastiaensen [0404 10:04]: > On Fri, 23 Apr 2004 11:15:16 -0400, Richard Lionheart wrote: > > > notes =< > I didn't like to_s' output for an Array of strings. > > Array#to_s simply concatenated them > > or inserted a comma separator. > > So I wrote my own. > > > > class MyArrayType < Array > > def to_s > > print "Starting MyArrayType#to_s" > > s = "" > > s.each { |x| s += "; " if s.length>0; s += x.to_s } > > s > > end > > end > > > > myA1 = MyArrayType.new > > myA1 = %w[x1, y1] > > puts myA1.to_s # x1,y1 .... expected x1; x2 .... MyArrayType#to_s not > > invoked > > > > Hi, > if all you want to do is change the to_s method, why not > just add it to Array? > > class Array > def my_to_s > join("; ") > end > end > > a = %w[x1 y1] > puts a.my_to_s Trouble is some other Array using method may expect tho old behaviour, but you can do this on a per instance basis: 0rasputin@lb:rasputin$ ruby instancedef.rb before override: a = foobarack, b = eenymeenymineymo after override: a = foo:bar:ack, b = eenymeenymineymo 0rasputin@lb:rasputin$ cat instancedef.rb a = [] b = [] a = %w( foo bar ack) b = %w(eeny meeny miney mo) puts "before override: a = #{a.to_s}, b = #{b.to_s}" def a.to_s self.join(':') end puts "after override: a = #{a.to_s}, b = #{b.to_s}" 0rasputin@lb:rasputin$ -- Is it possible that software is not like anything else, that it is meant to be discarded: that the whole point is to always see it as a soap bubble? Rasputin :: Jack of All Trades - Master of Nuns