Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose or here documents in ruby?

Tags:

heredoc

ruby

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,

like image 776
Ikaso Avatar asked Feb 26 '23 23:02

Ikaso


1 Answers

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

like image 82
Mark Rushakoff Avatar answered Mar 07 '23 13:03

Mark Rushakoff