2

I've come across this a few times, but never really understood it. Can someone explain to me how this syntax creates a string?

STRING = <<-EOS
This is a string!!
EOS

puts STRING
=> "This is a string!!"

As first I thought there was something special about the <<-EOS, but it actually appears to work with any char. <<x for instance also works

Can someone explain to me what exactly this syntax means? And how it is that a string is created?

1 Answer 1

9

It's called a heredoc, and this feature is built into the parser.

You can change the EOS to whatever string you want. The reason for that is so that if you have to put the word EOS (or a quotation mark) in your string for some reason, you can pick a convenient signal for the end of the string that doesn't also appear in the string, so you don't have to escape anything in the string.

Sign up to request clarification or add additional context in comments.

2 Comments

To extend what Ken said, heredocs are used in a lot of languages, including shell and Perl. They can be very powerful as templates because you can embed variables in them, similar to regular strings, making it easy to build formatted text quickly.
thx, good explanation! Link to the docs from kurumi explained it all for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.