Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace ' with \' in Ruby?

Tags:

string

ruby

gsub

I'm trying to figure out how to replace a quote like ' with something like \'.

How would I do this?

I have tried

"'".gsub("'","\\'")

but it just gives an empty string. What am I doing wrong here?

like image 896
Earlz Avatar asked Feb 15 '10 14:02

Earlz


People also ask

How do I 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") .

How do you replace a string with another string in Ruby?

Using the sub and gsub Methods 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 sub and gsub method in the string class.

How do you find and replace in Ruby?

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.

How do you replace a character in Ruby?

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.


2 Answers

How about this

puts "'".gsub("'","\\\\'")
\'

The reason is that \' means post-match in gsub (regex) and because of that it needs to be escaped with \\' and \ is obviously escaped as \\, ending up with \\\\'.

Example

>> "abcd".gsub("a","\\'")
=> "bcdbcd"

a is replaced with everything after a.

like image 132
Jonas Elfström Avatar answered Sep 21 '22 16:09

Jonas Elfström


The $' variable is the string to the right of the match. In the gsub replacement string, the same variable would be \' -- hence the problem.

x = "'foo'"
x.gsub!(/'/, "\\'")
puts x.inspect        # foo'foo

This should work:

x = "'foo'"
x.gsub!(/'/, "\\\\'")
puts x.inspect
puts x
like image 22
FMc Avatar answered Sep 23 '22 16:09

FMc