Reputation: 37324
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?
Upvotes: 43
Views: 44763
Reputation: 1778
String.gsub should do the trick.
Quoting docs:
gsub(pattern, replacement) → new_str
Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g.
\\d
will match a backlash followed byd
, instead of a digit.
Upvotes: 83
Reputation: 138100
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.
Upvotes: 8