Ruby: Quote Long String, Heredoc

By Xah Lee. Date:

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"

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables