Reputation: 2012
I want a string such as "This is Bob's sentence" to be modified to be "This is Bob\'s sentence"
My research seems to indicate that the following should work
"This is Bob's sentence".gsub("'", "\\'")
But the result I get is
"this is Bobs messages message"
I'm doing this in a rails app. Perhaps something else in the app is causing the issue? If you could please inform me of a ruby method which you know should work I would greatly appreciate it. Thanks in advance.
Upvotes: 1
Views: 56
Reputation: 441
This is annoying, but here's a solution that works:
sentence = "This is Bob's sentence"
sent_arr = sentence.gsub("'", "\\").split('')
sent_arr.each_index.select{|i| sent_arr[i] == "\\"}.each{|i| sent_arr.insert(i+1, "'") }
final_sentence = sent_arr.join
puts final_sentence
Basically:
"'"
with "\\"
(which is counted as only one index), make an array out of it."\\"
in the array, insert a "'"
at the position just after each.Even though the variable will seem to have two instances of the backslash (\\
), when you puts
the variable, you'll see that it only has one.
(Ironically, even StackOverflow escapes the backslashes in this response if you don't put it in code form... I had to put 3 backslashes to make it look like 2!)
Upvotes: 0
Reputation: 2012
Per thread referenced by mu is too short
"This is Bob's sentence".gsub("'", "\\\\\'")
Upvotes: 1
Reputation: 11226
You can use the capture like this:
puts "This is Bob's sentence".gsub(/(\w\')/, '\1\\')
This is Bob'\s sentence
You capture in a regular expression what's inside parens ()
and then you can modify it with \1
. You can have more than one capture group, they are numbered in order as they appear.
For more see similar example https://ruby-doc.org/core-2.7.0/String.html#gsub
Upvotes: 1