Ruby multiple string replacement

ruby string replace
ruby replace character in string
ruby replace all occurrences in string
ruby replace multiple characters in string
ruby gsub
ruby replace string in array
ruby gsub capture group
ruby regex
str = "Hello☺ World☹"

Expected output is:

"Hello:) World:("

I can do this: str.gsub("☺", ":)").gsub("☹", ":(")

Is there any other way so that I can do this in a single function call?. Something like:

str.gsub(['s1', 's2'], ['r1', 'r2'])

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.

Like this:

'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
'(0) 123-123.123'.gsub(/[()-,. ]/, '')    #=> "0123123123"

In Ruby 1.8.7, you would achieve the same with a block:

dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
   dict[match.to_s]
 end #=> "h3ll*"

Ruby : multiple string substitution in string template, The easiest way to substitute multiple strings into a string template is using "%" method of String class. In order to reuse the template we can assign it to a variable and pass the substituents into "%" method as an array or Hash. Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string. myString = "Welcome to JavaScript!"

Set up a mapping table:

map = {'☺' => ':)', '☹' => ':(' }

Then build a regex:

re = Regexp.new(map.keys.map { |x| Regexp.escape(x) }.join('|'))

And finally, gsub:

s = str.gsub(re, map)

If you're stuck in 1.8 land, then:

s = str.gsub(re) { |m| map[m] }

You need the Regexp.escape in there in case anything you want to replace has a special meaning within a regex. Or, thanks to steenslag, you could use:

re = Regexp.union(map.keys)

and the quoting will be take care of for you.

Ruby – Multiple string replacements with gsub, For making multiple substitutions in a string in one call of gsub, you could do something like this matchers = {'some_term1'� You can also make substitutions to replace one part of a string with another string. For instance, in an example string (foo,bar,baz) replacing "foo" with "boo" in would yield "boo,bar,baz." You can do this and many more things using the suband gsubmethod in the string class. Many Options for Ruby Substitution

You could do something like this:

replacements = [ ["☺", ":)"], ["☹", ":("] ]
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}

There may be a more efficient solution, but this at least makes the code a bit cleaner

Replacing Multiple Patterns in a Single Pass, Replacing Multiple Patterns in a Single Pass / Strings from Ruby Cookbook. The naive solution is to simply string together multiple gsub calls. The following� The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. All of these methods perform a search-and-replace operation using a Regexp pattern. sub! and gsub! modify the string on which they are called whereas the sub and gsub returns a new string, leaving the original unmodified.

Late to the party but if you wanted to replace certain chars with one, you could use a regex

string_to_replace.gsub(/_|,| /, '-')

In this example, gsub is replacing underscores(_), commas (,) or ( ) with a dash (-)

3 Awesome Ways To Use Ruby's Gsub Method, Replace text in a string using the Ruby Gsub Method. Because you use gsub on a string to replace parts of it. In fact: Replace Multiple Terms With A Hash. Ruby program that uses sub with regexp value = "cat and dog" # Replaced at a matching the regexp with another string. value. sub! (/c\w\w/, "bird") puts value Output bird and dog Regexp pattern c The lowercase letter "c". \w A word character (letter or digit).

You can also use tr to replace multiple characters in a string at once,

Eg., replace "h" to "m" and "l" to "t"

"hello".tr("hl", "mt")
 => "metto"

looks simple, neat and faster (not much difference though) than gsub

puts Benchmark.measure {"hello".tr("hl", "mt") }
  0.000000   0.000000   0.000000 (  0.000007)

puts Benchmark.measure{"hello".gsub(/[hl]/, 'h' => 'm', 'l' => 't') }
  0.000000   0.000000   0.000000 (  0.000021)

How to Use String Substitution in Ruby, How to Use String Substitution in Ruby. Using the sub and gsub Methods. Share; Flipboard; Email. Man working at computer with multiple� You can use the + operator to append a string to another. In this case, a + b + c, creates a new string. Btw, you don’t need to use variables to make this work. Example: puts "I like" + " " + "chocolate" # I like chocolate. puts "I like" + " " + "chocolate". # I like chocolate.

gsub (String), gsub. Importance_5. Ruby latest stable (v2_5_5) - 5 notes - Class: String If replacement is a String it will be substituted for the matched text. It may contain� Strings in Ruby are objects, and unlike other languages, strings are mutable, which means they can be changed in place instead of creating new strings. You’ll use strings in almost every program you write.

jedld/multi_string_replace: A fast multiple string replace , A fast multiple string replace library for ruby. Uses a C implementation of the Aho –Corasick Algorithm based on� So here's a quick cheatsheet for multi-line strings in Ruby 2.1. The simplest solution is something like this: [ "This is the first line.", "This is the second line.", "1 + 1 is # {1 + 1}." ].join(" ") + " " # => "This is the first line. This is the second line. 1+1 is 2. ".

Ruby String Replacement, Substitution and Insertion, We will also take a look at the Ruby chomp and chop methods. Contents. Changing a Section of a String. Ruby� You have learned about the gsub method in Ruby! It’s a powerful method that allows you to replace, or substitute characters inside a string. It has multiple uses: Removing invalid characters (by making the 2nd argument an empty string) Replacing placeholders & acronyms by their full values; Using patterns & logic to change a string

Comments
  • Is there a reason why you want to do that in one call? I would prefer to stick with your first solution.
  • @Semyon: The mapping table couple be large or it could be configured at run time.
  • On a similar note, if you end up having a huge mapping table - you are basically looking at a templating language. You can, in that case, convert it into a DSL and write an interpreter (or compiler) for that.
  • I had expected String#tr to do the trick, but the replacements being multiple charcters means I can't use that.
  • woah! I had no idea! great stuff!
  • Cool, didn't know about that. Kind of a nicer version of Perl tr.
  • Note that this is not the same as calling str.gsub(key, value) on every element of the hash. If something is matched by the regexp but doesn't have an entry in the hash, it will be deleted.
  • @NarenSisodiya, actually it should be: '(0) 123-123.123'.gsub(/[()\-,. ]/, '') You need to add the escape character to '-'.
  • Yeah that line there is wrong: '(0) 123-123.123'.gsub(/[()-,. ]/, '') You either need to escape the dash or move it to the front.
  • @steenslag: That's a nice modification.
  • String#gsub accepts strings as the pattern parameter: "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.".
  • @Andrew: Yeah but we have multiple strings to replace, hence the regex.
  • what if the keys of the map are regex expressions? the replacement doesn't seem to work
  • @content01: Off the top of my head, I think you'd have to go one by one in that case: map.each { |re, v| ... }