From: Joel VanderWerf Date: 2003-03-12T11:31:10+09:00 Subject: Re: How to add a destructive method to the String class... Jeremy wrote: > Hi, > > I just started learning Ruby this weekend, and I have to say that I've > fallen in love with it so far. It's a beautiful beautiful language. =0) It only gets better as you learn and use it :) > In messing around with it, 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? In other words, rather than having to do an assingment like > this: > > title = "This is the title" > > title = title.capwords > > 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"