Ruby: Quote Long String, Heredoc

By Xah Lee. Date: . Last updated: .

Using Different Brackets to Quote String

You can use a bracketing operator to quote a long string.

Literal string. Similar to single quote 'text'.
Evaluated string. Similar to double quote "text".

Any variable, char escapes, Ruby code, are evaluated inside.

You can use other delimiters for either %q or %Q. For example:

This is useful if your string already contain quote characters. This way, you can change to a different bracket, so you don't need to do escapes in the string.

# ruby

# quote string that contain quote marks
xx = %q{Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, «and what is the use of a book,» thought Alice «without pictures or conversation?».}
# ruby

xx = 4

# quote string and also eval code inside
p %Q{#{xx} and #{1+2} and more} == "4 and 3 and more"


Like Perl, PHP, you have “heredoc” for quoting long string. Start with


where randomString is a contunious random string a to z, capital case or lowercase. End with the same


on a line by itself.

# ruby

aa = 4

bb = <<nHh9t
something something
big string
also code #{aa}

# the #{aa} becomes 4

If you want the text to NOT be interpolated, start your quote string with single quote mark, like this:

# ruby

yy = 4

xx = <<'cmxBS'
x is #{x}

p xx == "x is \#{x}\n"

If the delimiter string start are double quoted, it's also interpolated.

# ruby

x = 4

# interpolated
xx3 = <<zYMMy
x is #{x}

p xx3 == "x is 4\n"

Ruby String