views:

209

answers:

2

string.sub looks like it only replaces the first instance. Is there an option for that or another method that can replace all patterns? Can you do it inside a regex like perl?

(I think something like r/blah/blah/)

... and +1 to anyone who can tell me WHY ON EARTH does string.sub replace just the FIRST match?

+7  A: 

string.gsub should do the trick

Brian Young
w00t. Thanks. You would think that sub would do that as a default and then have an int param for replace the first N occurrences!
DJTripleThreat
DJ: no you wouldn't. If you want to replace the first match, then **SUB**stitute is your choice, if not **G**lobal **SUB**stitute is your choice.
The Wicked Flea
A: 

I could explain why sub just replaces the first match of a pattern, but I think the documentation does it so much better (from ri String#sub on the command line):

str.sub(pattern, replacement)         => new_str
str.sub(pattern) {|match| block }     => new_str

Returns a copy of _str_ with the _first_ occurrence of _pattern_
replaced with either _replacement_ or the value of the block.
Gareth