What does <<DESC mean in ruby?

谁说胖子不能爱 提交于 2019-12-02 03:32:22

问题


I am learning Ruby, and in the book I use, there is an example code like this

#...
restaurant = Restaurant.new
restaurant.name = "Mediterrano"

restaurant.description = <<DESC
One of the best Italian restaurants in the Kings Cross area, 
Mediterraneo will never leave you disappointed
DESC

#...

Can someone explain to me what <<DESC means in the above example? How does it differ from the common string double quote?


回答1:


It is used to create multiline strings. Basically, '<< DESC' tells ruby to consider everything that follows until the next 'DESC' keyword. 'DESC' is not mandatory, as it can be replaced with anything else.

a = <<STRING
Here
is
a
multiline
string
STRING

The << operator is followed by an identifier that marks the end of the document. The end mark is called the terminator. The lines of text prior to the terminator are joined together, including the newlines and any other whitespace. http://en.wikibooks.org/wiki/Ruby_Programming/Here_documents




回答2:


It allows the creation of multi-line string constants in a readable way. See http://en.wikibooks.org/wiki/Ruby_Programming/Here_documents.




回答3:


It is called a heredoc, or heredocument. It allows you to write multiline. You can test it in your terminal!



来源:https://stackoverflow.com/questions/12012121/what-does-desc-mean-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!