44

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?

1
  • 2
    For the same reason that Perl needs a g modifier to make substitutions global. Replace all is often what you want, but not always. Commented Dec 13, 2009 at 1:39

2 Answers 2

84

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
DJ: no you wouldn't. If you want to replace the first match, then SUBstitute is your choice, if not Global SUBstitute is your choice.
For further reference, here is the manual page.
8

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.

1 Comment

wow, i've been using ruby and rails for years. Today was the 1st time I typed ri something#method because of your post. I had no idea that feature was there! Been just googling the terms and find the docs that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.