Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
aarona Avatar asked Dec 13 '09 01:12

aarona


People also ask

How do you use Replace in Ruby?

First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .

What does .gsub do in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

How do you replace a pattern in a string?

replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do you replace multiple characters in a string in Ruby?

Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.


1 Answers

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.

like image 174
Brian Young Avatar answered Oct 05 '22 18:10

Brian Young