brad
brad

Reputation: 32335

Different way of creating ruby strings

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?

Upvotes: 2

Views: 4570

Answers (1)

Ken Bloom
Ken Bloom

Reputation: 58770

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.

Upvotes: 9

Related Questions