Ruby - String String Heredocs

Introduction

In Ruby you can create long strings spanning multiple lines between single or double quotes.

Many Ruby programmers prefer to use a string called a heredoc.

A heredoc is a block of text that starts by specifying an end marker, which is simply an identifier of your choice.

Here, I specify EODOC as the end marker:

hdoc1 = <<EODOC 

<<EODOC tells Ruby that everything following the previous line is a single string that terminates when the end marker is located.

The string is assigned to the variable, hdoc1.

Here is an example of a complete heredoc assignment:

Demo

hdoc1 = <<EODOC 
this is a tes #{"test".upcase}, 
test # from   ww w .ja va2  s  .  com
this is a test
EODOC 

puts hdoc1

Result

By default, heredocs are treated as double-quoted strings, so expressions such as #{"test".upcase} will be evaluated.

If you want a heredoc to be treated as single-quoted string, specify its end marker between single quotes:

Demo

hdoc2 = <<'EODOC' 
this is a tes #{"test".upcase}, 
test # ww  w . j  a va 2 s.c om
this is a test
EODOC 
puts hdoc2

Result

The end marker of a heredoc must, by default, be placed flush with the left margin.

If you want to indent it, you should use <<- rather than << when assigning the end marker:

Demo

hdoc3 = <<-EODOC 
this is a tes #{"test".upcase}, 
test #  ww w  .j  a va  2 s. co  m
this is a test
    EODOC 
puts hdoc3

Result

It is up to you to pick an appropriate end marker.

It is even legitimate to use a reserved word:

Demo

hdoc4 = <<def 
this is a tes #{"test".upcase}, 
test # from   w ww.ja v  a2 s  .  c om
this is a test

def 
puts hdoc4
     A variable to which a heredoc is assigned can be used just like any other  
string variable: 

puts( hdoc1 )

Result

Related Topic