fivetwentysix
fivetwentysix

Reputation: 7487

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.

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

Upvotes: 3

Views: 4139

Answers (3)

BF4
BF4

Reputation: 1084

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

Upvotes: 8

Kelsin
Kelsin

Reputation: 833

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

Upvotes: 0

Samuel
Samuel

Reputation: 38356

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

Upvotes: 2

Related Questions