aarona
aarona

Reputation: 37324

How can I replace every instance of a pattern in ruby?

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

Answers (2)

Brian Young
Brian Young

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 by d, instead of a digit.

Upvotes: 83

Gareth
Gareth

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

Related Questions