Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different way of creating ruby strings

Tags:

string

ruby

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?

like image 741
brad Avatar asked Aug 24 '26 00:08

brad


1 Answers

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.

like image 188
Ken Bloom Avatar answered Aug 25 '26 20:08

Ken Bloom