From: Jeremy Date: 2003-03-13T10:36:57+09:00 Subject: Re: How to add a destructive method to the String class... Joel VanderWerf wrote: >> I found that I needed a method that >> capitalizes all the words in a string, assuming that each word is >> seperated by a space. I did this, and it works fine: >> >> class String >> def capwords >> self.split.each { |word| word.capitalize! }.join(" ") >> end >> end >> >> It does what I need, but it got me thinking. How would I make this >> destructive? >> >> I'd like to do this instesad: >> >> title.capwords! > > You gotta use destructive methods to write a destrucive method. Not > fully tested... > > irb(main):001:0> string = "this is the string" > "this is the string" > irb(main):002:0> class String; def capwords!; gsub!(/\b[a-z]/) {|ltr| > ltr.upcase }; end; end > nil > irb(main):003:0> string.capwords! > "This Is The String" Thank you for this! This solves the problem that Gennady spoke of with the whitespace, which is very good indeed. Thanks again, Jeremy