How to Escape a Single Quote in Ruby

is it possible to escape character within single quotes in ruby?

The only characters that needs to be escaped in a single quoted string are '\\' (for backslash \) and '\'' (for single quote ' itself).

Escaping single quotes for shell

Well, backslash is how you escape in ruby strings. To escape it you need another backslash.

The is usually to add backslashes until it works

puts %q{["Tom's Market"]}.gsub("'", "'\\\\''")
# ["Tom'\''s Market"]

How to escape single quotes within single quoted strings

If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:

 alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234

Explanation of how '"'"' is interpreted as just ':

  1. ' End first quotation which uses single quotes.
  2. " Start second quotation, using double-quotes.
  3. ' Quoted character.
  4. " End second quotation, using double-quotes.
  5. ' Start third quotation, using single quotes.

If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.

Replace single quote with backslash single quote

The %q delimiters come in handy here:

# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivoir".gsub("'", %q(\\\')) #=> Cote d\'Ivoir

Escaping single quotes in Ruby

Do not write your own SQL escaping. Please, always use the methods provided by the appropriate database driver.

If you're using MySQL, either mysql or the newer mysql2 gem, there's an escape function that should handle this for you.

It's not entirely clear why you're writing SQL in the first place when most databases have some kind of import-from-file function. MySQL in particular has LOAD DATA INFILE which can read in many different formats if used correctly.

Ruby gsub doesn't escape single-quotes

\' means $' which is everything after the match.
Escape the \ again and it works

"Yaho'o".gsub("'", "\\\\'")

ruby on rails replace single-quotes with double-quote in a string

If that's the only case you're covering where you need to show some output in double quoted string then. How about something simple like following

str = "The result of the child is \"#{current_res}\" and the lowest grade is \"#{lowest_res }\" ."

You can escape quotes in double quoted strings.



Related Topics



Leave a reply



Submit