From: Robert Klemme Date: 2006-01-08T07:38:01+09:00 Subject: Re: One-liner for regex subsitition (with upcasing)! Donkey Agony wrote: > Robert Klemme wrote: >>> def methodB(s) # this doesn't work, "will" stays lowercase >>> s.sub(/w.ll/, '\0'.upcase) >>> end > >> You want the block form of sub: >> >>>> "I will drill for a well in walla walla >>>> washington.".sub(/w.ll/){|m| m.upcase} >> => "I WILL drill for a well in walla walla washington." > > Ahhhhhhh. I hope nobody's hurt. :-) >>>> "I will drill for a well in walla walla >>>> washington.".sub(/w.ll/){|m| m.upcase!} >> => "I WILL drill for a well in walla walla washington." > > What's the difference between `upcase` and `upcase!` in these > instances (i.e., inside the block)? In irb, those both seem to yield > the same result. In a program, I had to use `sub!` if modifying the > variable directly, i.e.: upcase! modifies in place - but it's not a problem here as the match string is a new instance anyway. In this case it boils down to upcase! being more efficint. > string1 = "I will drill for a well in walla walla washington." > string1.sub!(/w.ll/) { |m| m.upcase } > puts string1 > > (also same result whether using `upcase` or `upcase!` in the block...) Same story. >> It's the only reasonable thing to do here because you won't know the >> matched text before the RX actually matched and that is the point in >> time where you have to calculate the replacement. The non block form >> calculates the replacement *before* the invocation - of course you >> can use \\0, \\1 etc, to access parts - but you can't modify them. > > Bingo! It's so obvious once you see it. :) > > Thank you, Robert! You're welcome! robert