Ruby: Quote String

By Xah Lee. Date: . Last updated: .

Quote String Literally

Use single quote to quote string exactly. (literal string) \n has no special meaning inside single quote.

# 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 Sequence

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

# ruby
xx = "A\nB"
puts xx
# prints in 2 lines

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

String with Embeded Expression

To evaluate a variable or Ruby code within a string, use

#{…}

# ruby

# put variable value inside a string
aa = 4
bb = "#{aa} cats"
p bb == "4 cats"

# eval Ruby code inside a string
p "#{1+2} cats" == "3 cats"

Perl tip: Ruby's string quoting system is similar to Perl's. [see Perl: Quoting Strings]

Ruby String