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?
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") .
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.
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.
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.
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
.
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
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