Different way of creating ruby strings
I've come across this a few times, but never really understood it. Can someone expla开发者_开发知识库in 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?
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.
精彩评论