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. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables