CommonThread

Tip: Ruby Here Document

Posted by anthony crumley, Wed Dec 19 23:12:00 UTC 2007

“Here, document. Come here boy. That’s a good document.” Often times we need to create fairly complex strings in code. The result is usually multiple concatenations that tend to get a little wild and woolly. One solution is to put the string in a separate document or template that uses ERB. This can be overkill for a one-off situation. To tame this mess Ruby provides the here document. I assume the strange name comes from it being like putting the complex string in a separate document but it is right here instead of there.

Here documents begin with << or <<- followed by a word which will be the string terminator. If the document begins with << then the terminator must be in the left most column which doesn’t look good in most situations, although it does make the end easy to find.

The most straight forward use is assignment to a variable.

  xml = <<-XML_END
    <project>
      <owner>#{project.owner}</owner>
      <manager>#{project.manager}</manager>
    </project>
  XML_END

The here document can also be used as a parameter to a method. The first time I saw this one it freaked me out a little until I understood it.

def create(project, user)
  ...
end

update(<<PROJECT_XML, current_user)
  <project>
    <owner>#{project.owner}</owner>
    <manager>#{project.manager}</manager>
  </project>
PROJECT_XML

Filed Under: | Tags: anthony ruby tip

Comments

Have your say

A name is required. You may use HTML in your comments.




Recent Articles

Categories