The Ruby Here-doc
Here-docs in Ruby are a strange but sometimes useful beast. A subclass of String, they allow you to generate a set of data lines or a template using the << syntax. Here is a simple example:
text = <<EOM
Here is the first line of text.
You can put several lines of text as well.
They will all be saved with newlines intact.
EOM
The block begins with the << and any string as the delimiter, such as EOM (end of message). The ending delimiter has to be flush left and must be the only thing on its line.
The text block generated by the here-doc defaults to a double-quoted string, which allows for escape characters and interpolation. Putting the opening delimiter in single quotes: <<'EOM' generates the block as a single quoted string.
The opening << delimiter can be placed anywhere and will be replaced by the block that follows:
num = 5 * <<EOM.to_i
10
EOM
>> num
=> 50
It can also be used in a literal object constructor like so:
arr = [0, 5, <<EOM, 3]
This will be arr[3]
Check it out.
EOM
>> arr
=> [0, 5, "This will be arr[3]\nCheck it out.\n", 3]
The last possible use I will point out is in an argument list. This can be useful if you need to include a long string that might not fit well otherwise.
a_function_with_args(x, y, <<EOM)
This will be put into the function call as the third argument.
EOM
Which is equivalent to:
a_function_with_args(x, y, "This will be put into the function call as the third argument.")
Here-docs aren’t seen too often in Ruby, but used in the right context they can be a useful tool in the toolbelt.