Close

Ruby – Multiline String Variable (using heredoc)

Ruby supports the “heredoc” syntax for strings. Here’s an example:

Announcement

I have released my new course on Udemy, Kubernetes By Example. Sign up now to get free lifetime access!
string = <

This outputs:

PS C:\Temp\irb> ruby .\heredoc.rb
  This is the first line.
  This is the second line.
  This is the third and final line.
PS C:\Temp\irb>

Note, you can't put any spacing before the closing "EOS" terminator, otherwise it will fail. EOS has to start at the very beginning of the line. However you can override this by prefixing "-" at the opening delimiter:

string = <<-EOS
  This is the first line.
  This is the second line. 
  This is the third and final line. 
                  EOS

puts string

This time I was allowed to indent it. But the output remains the same.