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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?