From: "Ara.T.Howard" Date: 2004-04-24T00:44:13+09:00 Subject: Re: Problem assigning an Array object to an Array-subclass object On Fri, 23 Apr 2004, Richard Lionheart wrote: > [ I apologize if this is a second post. My earlier one seems to have gotten > lost in the ethernet :-) ] > > 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. > But as the last line indicates, I failed. > > Apparently, array assignment to myA1 > changed the reference from a MyArrayType object > to an Array object. > > Two questions: > 1. How can I set myA1 to an array value > and preserve it's type? > 2. Isn't there a "Ruby way" to set the separator > (I thought there was some special symbol a la Perl > but I couldn't find any in Thomas' or Fulton's > books.) > NOTES > > 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 try this: class MyArrayType < Array def to_s join ';' end end myA1 = MyArrayType['x1', 'y1'] puts myA1.to_s # => x1;y1 puts myA1 # => x1\ny1 your statement: > Apparently, array assignment to myA1 > changed the reference from a MyArrayType object > to an Array object. was correct what you did i just like myA1 = MyArrayType.new myA1 = 'fubar' so, of course, your method was not called something else to be aware of: - Object#puts behaves different if passed an Array, or sub-class of Array, see above in general it can be tricky to inherit from the built-ins. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | URL :: http://www.ngdc.noaa.gov/stp/ | TRY :: for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done ===============================================================================