tags:

views:

38

answers:

1

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!”' 
+3  A: 

The backslashes are only showing up in irb due to the way it prints out the result of a statement. If you instead pass the gsubed string to another method such as puts, you'll see the "real" representation after escape sequences are translated.

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

Note also that after the output of puts, we see => nil indicating that the call to puts returned nil.

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 in gsub:

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

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:

1.9.0 > '"' == 34.chr
 => true 
1.9.0 > %q{"} == 34.chr
 => true 
1.9.0 > "\"" == 34.chr
 => true 
Mark Rushakoff