Introduction
A heredoc can be a nice way of passing a large block of text around in a script. Here are a few tips on using heredocs with Ruby.
Literal heredoc
A "regular" heredoc will take all the characters literally, including
any whitespace. If you include the -
in the heredoc name, it will not
require the closing tag to be indented all the way to the left.
#!/usr/bin/ruby
# heredoc_literal.rb
text = <<-EOF
This is a
fully literal
heredoc.
EOF
puts text
Outputs:
This is a
fully literal
heredoc.
Stripped heredoc
If you want to maintain indentation to keep your source code formatting
looking nice, you can indent your heredoc and automatically strip the leading whitespace by
changing the -
to a ~
in the heredoc definition. This is new in Ruby 2.3.
I put the content inside a function so there was indentation to demonstrate
how it strips the left content.
Also note how the name of the heredoc changed from EOF
to HEREDOC
. You
can name it anything you want as long as the closing tag matches the open tag.
#!/usr/bin/ruby
# heredoc_stripped.rb
def make_heredoc
<<~HEREDOC
This is
a stripped
heredoc with left
whitespace removed.
It only removes the amount of whitespace
that is started on the first line.
HEREDOC
end
puts make_heredoc
Outputs:
This is
a stripped
heredoc with left
whitespace removed.
It only removes the amount of whitespace
that is started on the first line.
Run Ruby code from heredoc
This isn't so much about how to use a heredoc within Ruby, but how to use a heredoc in the shell to pass a multi-line Ruby script directly in to the Ruby interpreter.
#!/bin/bash
# From bash/zsh/equivalent
/usr/bin/ruby <<EOF
puts 'This is a Ruby script being fed directly'
puts 'in to the Ruby interpreter'
EOF
This can be a cleaner option than trying to pass in a script by using the
-e
flag like this:
ruby -e "puts 'hi'; puts 'this script'; puts 'is jammed in to one line';"
Conclusion
Now you should have a basic grasp on how to use a heredoc with Ruby to pass around a large block of text.