Ruby: Quoting Strings

,

Ruby's string is very similar to Perl's. Single quote for literal, double quote to eval embedded variable or code.

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

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

aa = 'tiger'   # use single quote for string exactly as is
p aa       # prints 「"tiger"」

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

Use double quote for strings that contain 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:

This is similar to Perl's q{‹…›} and qq{‹…›}. For examples of %q{‹…›} and “heredoc”, see: Ruby: Quoting Long String and Heredoc.

blog comments powered by Disqus