From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2002-02-02T10:55:20+09:00 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