Escaping Single and Double Quotes in a String in Ruby

Ruby escape double quotes

Use heredoc, it even reads better:

iframe_name = page.execute_script <<JS
$('#card-element').find('[name*="__privateStripeFrame"]').first().attr('name')
JS

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.

Ruby single and double quotes

In Ruby, double quotes are interpolated, meaning the code in #{} is evaluated as Ruby. Single quotes are treated as literals (meaning the code isn't evaluated).

var = "hello"
"#{var} world" #=> "hello world"
'#{var} world' #=> "#{var} world"

For some extra-special magic, Ruby also offers another way to create strings:

%Q() # behaves like double quotes
%q() # behaves like single quotes

For example:

%Q(#{var} world) #=> "hello world"
%q(#{var} world) #=> "#{var} world"

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).

Double vs single quotes

" " allows you to do string interpolation, e.g.:

world_type = 'Mars'
"Hello #{world_type}"

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.



Related Topics



Leave a reply



Submit