From: David Flanagan Date: 2007-11-16T04:30:56+09:00 Subject: Re: Thoughts about Array#compact!, Array#flatten!, Array#reject!, String#strip!, String#capitalize!, String#gsub!, etc. Matz has added Object.tap to Ruby 1.9 which is intended for use in method chains and can be used to solve htis problem: "20Mb string".tap {|s| s.downcase!}.split.... If you want to use it in 1.8, it is trivial: class Object def tap yield self self end end Hope this helps, David Wolfgang N��dasi-Donner wrote: > Good evening all together! > > I didn't find discussions about that in clr or ruby-core, so I hope it > isn't already discussed long ago. > > The methods listed in the header return "nil" when nothing was done. > This may be usefull and used in several situations. > > Unfortunately there is possible usage of these methods, when this return > value is a very bad thing: In a method-chain like... > > "I am a 20MB string".downcase.split(/\s+/).reject{|s|s.length>20} > > In this case the initial string, the result of "downcase", and of > "split" will only be used once - they are single threaded. If, as the > example text will name, the original String object is about 20MB, > "downcase" will produce a copy, which will be thrown away. The same is > true for "reject". It would be much better to use... > > "I am a 20MB string".downcase!.split(/\s+/).reject!{|s|s.length>20} > > ...but this is not possible, because "downcase!" and "reject!" will > return "nil" if they have nothing to do. > > It is very easy to build a workaround - e.g. for "reject"... > > class Array > def reject_ch(&b) > self.reject!(&b) > self > end > end > > ...which guarantees that the changed Array will always be returned. > > My proposal IS NOT to change the existing "!" methods, because they may > have substancial usage, but to add methods to Array, String, and > possibly other classes, that change the objects in place and do always > return them. > > I have no ideas about naming (I also have no ambitions in giving names), > but I think the functionality will be useful in these standard Ruby > classes. > > Wolfgang N��dasi-Donner >