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 gsub
ed 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