From: Jeff Putsch Date: 2001-06-27T05:37:43+09:00 Subject: [ruby-talk:16933] [Newbie] overload + operator for instance variable Howdy, I'm trying to implement a simple class and want to overload the "+" operator for instances of that class. I want to overload the "+" operator for specific instance variables only. Here is what I've tried: class Category def initialize(name, desc = "") @name = name @desc = strToArray(desc) end def desc=(newDesc) @desc = strToArray(newDesc) end def @desc.+(otherDesc) # def desc.+(otherDesc) @desc = @desc | strToArray(otherDesc) # gives NameError $stderr.write("In overloaded +\n") # this is never reached end def desc @desc.join(', ') end def strToArray(aDesc) aDesc.chomp.strip.split(/,\s*/) end private :strToArray 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. It appears that the "c.desc += "d,f,g" line is first calling the attribute reader for desc and returning a string, probably because the right-hand side of the "+" operator is a string, then concatenating the strings, then calling the desc=() attribute writer. What I would like to have happen is have my overloaded "+" operator method called when I do things like c.desc = c.desc + "a,b,c". Any guidance will be appreciated. I may have to store the @desc as the comma separated string and convert to/from arrays in the attribute write to weed out common entries, e.g. "a,b,c,a" -> "a,b,c" Thanks, Jeff.