From: Edgardo Hames Date: 2004-10-06T03:38:04+09:00 Subject: Re: Extending existing classes (was: Re: A ruby course) On Wed, 6 Oct 2004 03:29:35 +0900, Henrik Horneber wrote: > >> - extending String so you can tell it to remove cpp comments /* remove > >> me */ > > > > Extending string with something like remove_cpp_comments seems awkward > > to me. In any usecase for this I'd rather have a class CppCode that I > > can ask to remove_comments. (Or even better, to give me the source > > without comments.) > > > > So my personal heuristic tells me not to extend in this case. > > Now, the reason I was immediatly reminded of that remove_cpp_comments > example is, that I wrote a small script some time ago, which used > exactly this case. First, I implemented remove_cpp_comments in its own > class (which was not called CppCode, but had the same intend), but out > of curiosity (and because in ruby I can, dang it! :) ) I moved the > remove_cpp_comments method to String. Turns out, the method got shorter > and somewhat clearer, at least to me. And I could write something like > > source_code = IO.readlines(file).join("\n") > source_code.strip_comments! > # instead of source_code = CppCode.strip_comments( source_code) > > .... you get the idea. > > Even though the code became clearer on that level, I still have to agree > with Brian that it is somehow dirty/awkward on a different level to > extend String with such a method. > I usually try not to do that kind of things. Then, for each new lanaguage you are going to support, you should now add a remove_#{lang}_comments to String. But then, when reading a given source file you could remove comments that are not so in that language. Regards, Ed -- " Don't relax! It's only your tension that's holding you together."