Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multiple string replacement

Tags:

string

ruby

gsub

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']) 
like image 473
Sayuj Avatar asked Nov 15 '11 06:11

Sayuj


People also ask

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.

How do you replace a string 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") .

How do I use GSUB 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 I replace multiple strings in R?

Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.


1 Answers

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*" 
like image 70
Naren Sisodiya Avatar answered Sep 20 '22 20:09

Naren Sisodiya