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

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]