Ruby: Quote String

By Xah Lee. Date: . Last updated: .

Quote String Literally

Use single quote to quote string exactly. (literal string)

# -*- coding: utf-8 -*-
# ruby

# use single quote for string exactly as is

aa = 'tiger'
p aa # prints "tiger"

# single quoted string containing newline or tab will be printed as they are
cc = 'a
b'

print cc # prints 2 lines

String with Escape and Embeded Expression

Use double quote for string that contains newline escape \n, or include variable values or Ruby code.

# -*- coding: utf-8 -*-
# ruby
mm = "tiger\nsnake"
puts mm # prints each word in separate line

You can use \n for newline, and \t for tab, etc.

To evaluate a variable or Ruby code within a string, use #{…}.

# -*- coding: utf-8 -*-
# ruby

# put variable value inside a string
aa = 4
bb = "there are #{aa} tigers"
p bb # prints “there are 4 tigers”

# eval Ruby code inside a string
p "there are #{1+2} tigers" # prints “there are 3 tigers”

For long string, you can also use:

(note: Ruby's string quoting is very similar to Perl's.)

This is similar to Perl's q{…} and qq{…}.

[see Ruby: Quote Long String, Heredoc]

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?