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?
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") .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With