Ian Amuhton
1/7/2006 6:48:00 PM
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 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.:
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...)
> 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!
--
da
~~