From: andrew_queisser@... (andrew queisser) Date: 2002-02-02T09:15:16+09:00 Subject: Re: Newbie question Oliver Mensinger wrote in message news:... > Andrew, > > what do you think about that: > > class String > def getCommaElements(quantity) > if self =~ /(\w+,*){0,#{quantity}}/ > $&.gsub(/,$/, '') > end > end > end > > line = "1,2,3,4,5,6,7" > puts line.getCommaElements(4) # 1,2,3,4 > puts line.getCommaElements(7) # 1,2,3,4,5,6,7 > > HTH, Oliver. > 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? Thanks, Andrew