Ruby: Quoting Long String and Heredoc

,

Using Different Brackets to Quote String

You can use a bracketing operator to quote complex string.

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.

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

# quote string that contain quote marks
aa = %q{'1' "2" (3) [4] {5}}
p aa                         # ⇒ "'1' \"2\" (3) [4] {5}"
# -*- coding: utf-8 -*-
# ruby

aa = 4

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

Heredoc

Like Perl, PHP, you have “heredoc” for quoting long string. Start with <<‹AAA› where ‹AAA› is a contunious random string. End with ‹AAA› on a line by itself.

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

aa = 4

bb = <<HHHHHHH
multi-line big string
that may contain quote marks " " ' '
also code #{aa}
HHHHHHH

puts bb

# multi-line big string
# that may contain quote marks " " ' '
# also code 4

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

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

x = 4

myText1 = <<'tttt'
x is #{x}
tttt
p myText1                        # ⇒ "x is \#{x}\n"

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

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

x = 4

# interpolated
myText3 = <<tttt
x is #{x}
tttt
p myText3                        # ⇒ "x is 4\n"

# interpolated
myText2 = <<"tttt"
x is #{x}
tttt
p myText2                        # ⇒ "x is 4\n"
blog comments powered by Disqus