What are <— Ruby Strings called? And how do I insert variables in them?

倾然丶 夕夏残阳落幕 提交于 2019-11-30 06:01:34

问题


<-- Seems to be unsearchable on the web so had to ask the question here.

What is their searchable name, and how do I add variables inline?


回答1:


That syntax is for declaring a HERE DOCUMENT http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#here_doc

There's a line-oriented form of the string literals that is usually called as `here document'. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string. If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.

If the - placed before the delimiter, then all leading whitespcae characters (tabs or spaces) are stripped from input lines and the line containing delimiter. This allows here-documents within scripts to be indented in a natural fashion.

Regarding interpolation, the link gives more details, but it is like a double quoted string if your string is delimited as below (ignore this page's color formatting)

<<-HERE
   I can interpolate #{foo}
HERE

whereas it is like a single quoted string

<<-'HERE'
 This will print out #{foo} as text
HERE

Also the original pickaxe is a good source http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html




回答2:


<<-FOO is a here document. You can read more about them here.

And regular interpolation works in here docs as well.

str = <<-STR
  #{foo}
STR



回答3:


<<HEREDOC
This is like a double quoted string
Interpolation happens here. #{1+2}
Backslashes are interpreted as escapes. \a\t
HEREDOC

http://jeff.dallien.net/posts/optional-behavior-for-ruby-heredocs



来源:https://stackoverflow.com/questions/6951446/what-are-ruby-strings-called-and-how-do-i-insert-variables-in-them

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