开发者

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

<-- Seems to be unsearchable on the web so had to ask the question here.开发者_JS百科

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


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


<<-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


<<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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜