From: Jeff Putsch Date: 2001-06-27T07:05:42+09:00 Subject: [ruby-talk:16936] Re: [Newbie] overload + operator for instance variable Thanks, Your suggestion works like a charm. Jeff. On Wed, Jun 27, 2001 at 06:02:54AM +0900, Avi Bryant wrote: > On Wed, 27 Jun 2001, Jeff Putsch wrote: > > > def desc=(newDesc) > > @desc = strToArray(newDesc) > > end > > def desc > > @desc.join(', ') > > end > > > c = Category.new > > c.desc = "a,b,c" # --> c's @desc = ["a", "b", "c"] > > c.desc += "d,f,g" # --> c's @desc = ["a", "b", "cd", "f", "g"] > > > > As you can see, I'm attempting to store the desc as an array, yet pass > > in comma-delimited strings. > > Well, I'm not sure I would personally use operator overloading for this, > but if you really want it, you could maybe change your accessor to > > def desc > descString = @desc.join(',') > def descString.+(str) > "#{self}, #{str}" > end > descString > end > > Note that it doesn't make sense to override an operator for a particular > instance variable - a variable is just a slot, it has no type, and no > methods. What I'm doing here is overriding an operator for a particular > object - in this case, the string being returned from desc. > > Avi >