From: Rich Kilmer Date: 2002-02-02T11:08:52+09:00 Subject: RE: Newbie question > -----Original Message----- > From: Phil Tomson [mailto:ptkwt@shell1.aracnet.com] > Sent: Friday, February 01, 2002 8:55 PM > To: ruby-talk ML; undisclosed-recipients: > Subject: Re: Newbie question > > > In article , > andrew queisser wrote: > >Oliver Mensinger wrote in message > >news:... > >Thanks, that almost gets me there. I wasn't clear enough in my > >original post but the "words" could consist of any characters other > >than comma. They include spaces, dashes, etc. I'm sure the regexp > >could be modified to account for that. > > > >Your post brings up another question: I noticed you're adding a > >function to the String class. My first thought was (my primary > >language is C++) "shouldn't we derive a new class and add the function > >there." Then I realized that I have a loop in my program that does a > >File.each_line and the extended string class dovetails nicely into the > >loop. I just call your new function on the block parameter (which is a > >String) like so: > > > > infile.each_line do |line| > > ofile.puts line.getCommaElements(4) > > end > > > >Very nice. Then I started thinking about extending well-known classes > >in general and I'm wondering whether injecting new functions is such a > >good idea. After all, I could change my loop to this: > > > > infile.each_line do |line| > > ofile.puts CommaElementSearcher(line, 4) > > end > > > >where CommaElementSearcher is a new function (or class) that handles > >the same functionality. > > > >So, what are the feelings about cost/benefit of modifying existing > >classes in this way? Are there hidden dangers or is it a good thing? > > I think it tends to be a cultural thing. Apparently in SmallTalk this is > also a common practice. I can see why it would be problematic in the C++ > world because it really isn't as easy to do in C++ (actually, is it even > possible in C++ at all to modify an existing class and have all current > objects of that class respond accordingly? - I doubt it). > > You probably should use caution in changing the way an existing method > of a class works, though. For example, it probably wouldn't be a good > idea to change Array#each to do something different than it currently > does. But adding methods to a built-in class, as in your example, is > fairly common practice in the Ruby community. > > Phil This is fine especially if you are writing a script that simply needs to redefine the class while its running. If you are producing a library that others are going to use and your modification is going to be part of their runtime environment, that may pose a larger problem. For example, someone else's library may make use of adding a method to String with the same name as yours, but with different functionality. In that case it may make more sense to build a module to contain the function "getCommaElements(line)" which allows you to isolate the funtion away from others. -rich