From: Jamis Buck Date: 2003-12-03T12:53:21+09:00 Subject: Re: What's the best way to create methods dealing with an object of a certain class? Lyle Johnson wrote: > Leif K-Brooks wrote: > > > I want to add a method to be run on Strings. Currently, I'm just > > adding it on to the String class. Should I be subclassing it > > instead? Creating a method which takes a String as an argument? > > I have mixed feelings about re-opening built-in classes (like String) > to add new methods to them, even though the provision for this is one > of Ruby's attractions. My concern is that people get used to the > built-ins and expect certain standard behaviors from them; augmenting > or otherwise changing them could create confusion for other people > looking at your code. I agree with Lyle, but only if you are modifying the behavior of an existing feature of the class. For instance, changing the + operator to do something wierd to a string instead of concatenation is just wrong. However, modifying existing classes to augment their behavior by adding new features is something I find to be very natural. Just the other day I wanted a method that would tell me how many initial letters two strings had in common. Rather than having a utility method that would do it, and which would feel very *un*-object-oriented, I added a method to string and could say: prefix_length = string1.prefix_length( string2 ) As Lyle said, though, there is no right or wrong answer here. I think it completely depends on personal preference. - Jamis