Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single and double quotes in a string in ruby?

Tags:

ruby

escaping

How can I escape single and double quotes in a string?

I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.

e.g: str = "ruby 'on rails" " = ruby 'on rails"

like image 775
Aleem Avatar asked Jul 15 '11 10:07

Aleem


People also ask

How do you escape a single quote in Ruby?

The easiest way is to use escape_javascript http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html it "Escapes carriage returns and single and double quotes for JavaScript segments."

How do you escape a single quote in a double quote?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do you escape a double quote in query string?

Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said.


2 Answers

My preferred way is to not worry about escaping and instead use %q, which behaves like a single-quote string (no interpolation or character escaping), or %Q for double quoted string behavior:

str = %q[ruby 'on rails" ] # like single-quoting str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable 

See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings.

like image 172
Rob Di Marco Avatar answered Sep 25 '22 08:09

Rob Di Marco


Use backslash to escape characters

str = "ruby \'on rails\" " 
like image 35
gaurav.singharoy Avatar answered Sep 23 '22 08:09

gaurav.singharoy