What is the purpose or here documents in ruby?
Question
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,
Solution
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).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow