Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a single quote in Ruby?

I am passing some JSON to a server via a script (not mine) that accepts the JSON as a string.

Some of the content of the JSON contains single quotes so I want to ensure that any single quotes are escaped before being passed to the script.

I have tried the following:

> irb > 1.9.3p194 :001 > x = "that's an awesome string" >  => "that's an awesome string"  > 1.9.3p194 :002 > x.sub("'", "\'") >  => "that's an awesome string"  > 1.9.3p194 :003 > x.sub("'", "\\'") >  => "thats an awesome strings an awesome string" 

but can't seem to get the syntax right.

like image 448
Dave Sag Avatar asked Oct 03 '12 00:10

Dave Sag


People also ask

How do you escape a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

Can you use single quotes in Ruby?

Best practice. As most of the Ruby Linters suggest use single quote literals for your strings and go for the double ones in the case of interpolation/escaping sequences.


2 Answers

The reason sub("'", "\'") does not work is because "\'" is the same as "'". Within double quotes, escaping of a single quote is optional.

The reason sub("'", "\\'") does not work is because "\\'" expands to a backslash followed by a single quote. Within sub or gsub argument, a backslash followed by some characters have special meaning comparable to the corresponding global variable. Particularly in this case, the global variable $' holds the substring after the last matching point. Your "\\'" within sub or gsub argument position refers to a similar thing. In order to avoid this special convention, you should put the replacement string in a block instead of an argument, and since you want to match not just one, you should use gsub instead of sub:

gsub("'"){"\\'"} 
like image 77
sawa Avatar answered Sep 20 '22 23:09

sawa


Why aren't you using the JSON gem?

require 'json' some_object = {'a string' => "this isn't escaped because JSON handles it.", 'b' => 2}  puts some_object.to_json => {"a string":"this isn't escaped because JSON handles it.","b":2} 

And a round-trip example:

require 'pp' pp JSON[some_object.to_json] => {     "a string" => "this isn't escaped because JSON handles it.",         "b" => 2 } 

And an example with double-quotes:

some_object = {   'a string'       => "this isn't escaped because JSON handles it.",   'another string' => 'double-quotes get "escaped"' } puts some_object.to_json => {             "a string" => "this isn't escaped because JSON handles it.",       "another string" => "double-quotes get \"escaped\""   } 
like image 20
the Tin Man Avatar answered Sep 21 '22 23:09

the Tin Man