tags:

views:

48

answers:

1

Hi,

I have read about here documents on the book "The Ruby Programming Language" and didn't understand what is the purpose of here documents and when will you use it on production code. I would be happy if someone can explain and give some examples of usage.

regards,

+6  A: 

In any language that supports them, a heredoc is a convenient way to make a large string literal.

Take the following contrived Ruby script that takes your name and outputs source code for a C program that tells you hello:

#!/usr/bin/env ruby
name = $*[0]

unless name
  $stderr.puts "Please supply a name as the first argument to the program"
  exit 1
end

source = <<EOF
#include <stdio.h>

int main()
{
    puts("Hello, #{name}!");
    return 0;
}
EOF

puts source

Other than a heredoc, the other option to make the source is to specify it line-by-line, which becomes tedious and potentially error prone (especially when you have embedded quotes).

Mark Rushakoff
Thanks, for your help.
Ikaso
They work really well for simple inline templates, similar to an ERB template. They're not as flexible, but sometimes they're just the ticket.
Greg