DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Display A String With Double Quotes

04.03.2010
| 12697 views |
  • submit to reddit
        To escape quotes in a string %q (single quotes) and %Q (double quotes) are typically used e.g.
testing = "testing with \"quotes\""
puts testing      #=> testing with "quotes"
testing.inspect   #=> "\"testing with \\\"quotes\\\"\""

testing = %q(testing with "quotes")
puts testing      #=> testing with "quotes"

testing.inspect   #=> "\"testing with \\\"quotes\\\"\""

testing = %Q(testing with "quotes")
puts testing      #=> testing with "quotes"
testing.inspect   #=> "\"testing with \\\"quotes\\\"\""

testing = %q[testing with "quotes"]
puts testing      #=> testing with "quotes"
testing.inspect   #=> "\"testing with \\\"quotes\\\"\""

testing = %Q[testing with "quotes"]
puts testing      #=> testing with "quotes"
testing.inspect   #=> "\"testing with \\\"quotes\\\"\""

testing = %Q*testing with "quotes"*
puts testing      #=> testing with "quotes"
testing.inspect   #=> "\"testing with \\\"quotes\\\"\""


# -- with nested ruby code ---------

testing = "testing #{Time.now} with \"quotes\""
puts testing     #=> "testing 2010-04-03 10:25:14 +0100 with "quotes"
testing.inspect  #=> "\"testing 2010-04-03 10:25:14 +0100 with \\\"quotes\\\"\""

testing = %q(testing #{Time.now} with "quotes")
puts testing     #=> testing #{Time.now} with "quotes"
testing.inspect  #=> "\"testing \\\#{Time.now} with \\\"quotes\\\"\""

testing = %Q(testing #{Time.now} with "quotes")
puts testing     #=> "testing 2010-04-03 10:25:14 +0100 with "quotes"
testing.inspect  #=> "\"testing 2010-04-03 10:25:14 +0100 with \\\"quotes\\\"\""

testing = %q[testing #{Time.now} with "quotes"]
puts testing     #=> testing #{Time.now} with "quotes"
testing.inspect  #=> "\"testing \\\#{Time.now} with \\\"quotes\\\"\""

testing = %Q[testing #{Time.now} with "quotes"]
puts testing     #=> "testing 2010-04-03 10:25:14 +0100 with "quotes"
testing.inspect  #=> "\"testing 2010-04-03 10:25:14 +0100 with \\\"quotes\\\"\""

testing = %Q*testing #{Time.now} with "quotes"*
puts testing     #=> "testing 2010-04-03 10:25:14 +0100 with "quotes"
testing.inspect  #=> "\"testing 2010-04-03 10:25:14 +0100 with \\\"quotes\\\"\""

Resources:
 - <a href="http://en.wikibooks.org/wiki/Ruby_Programming/Alternate_quotes">Ruby Programming/Alternate quotes - Wikibooks, collection of open-content textbooks</a> [wikibooks.org]