Escape '' 'with regular double quotes using Ruby regex

I have text that has these fancy double quotes: `` '' and I would like to replace them with regular double quotes using Ruby gsub and regex. Here is an example and what I still have:

sentence = 'This is a quote, "Hey guys!"'  

I couldn't figure out how to escape double quotes so I tried using 34.chr:
sentence.gsub(""",34.chr).  This gets me close but leaves a back slash in front of the double quote:

sentence.gsub(""",34.chr) => 'This is a quote, \"Hey guys!"' 
+3
source share
1 answer

Backslashes appear only irbbecause of how it outputs the result of the instruction. If you pass the string gsubed to another method, for example puts, you will see a “real” representation after translating escape sequences.

1.9.0 > sentence = 'This is a quote, "Hey guys!"'  
 => "This is a quote, \342\200\234Hey guys!\342\200\235" 
1.9.0 > sentence.gsub('"', "'")
 => "This is a quote, 'Hey guys!\342\200\235" 
1.9.0 > puts sentence.gsub('"', "'")  
This is a quote, 'Hey guys!"
 => nil

, puts => nil, , puts nil.

, , - puts: , escape-, . gsub:

1.9.0 > puts sentence.gsub(/("|")/, 34.chr)
This is a quote, "Hey guys!"
 => nil

, Ruby - , - . , :

1.9.0 > '"' == 34.chr
 => true 
1.9.0 > %q{"} == 34.chr
 => true 
1.9.0 > "\"" == 34.chr
 => true 
+9

Source: https://habr.com/ru/post/1747114/


All Articles