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’s an example and what I have so far:
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!”'
The backslashes are only showing up in
irbdue to the way it prints out the result of a statement. If you instead pass thegsubed string to another method such asputs, you’ll see the “real” representation after escape sequences are translated.Note also that after the output of
puts, we see=> nilindicating that the call toputsreturnednil.You probably noticed that the funny quote is still on the end of the output to
puts: this is because the quotes are two different escape sequences, and we only named one. But we can take care of that with a regex ingsub:Also, in many cases you can swap single quotes and double quotes in Ruby strings — double quotes perform expansion while single quotes do not. Here are a couple ways you can get a string containing just a double quote: