How to Use Indention with Multiline Strings with the Squiggly Heredoc Syntax

Working with multiline strings in Ruby used to result in very odd looking code because heredocs required that you shift all of the string code so it was flush against the left hand side of the file. However, with modern versions of Ruby you are now able to utilize the squiggly heredoc syntax, which allows you to indent multiline strings in a file.

Summary

Refactor a multiline string in Ruby so that it can be indented.

Exercise File

Code File

Exercise Description

Given a multiline string, stored in a Ruby Heredoc, refactor it so that you can indent the string instead of having it flushed to the left-hand side of the file.

Standard Heredoc Example

<<~EOL
  Some
  words
  in a heredoc
EOL

# Results in:
  Some
  words
  in a heredoc
# Notice the spaces on the left hand side of the text

Required Output

Some
words
in a heredoc

Real World Usage

Working with multiline strings in Ruby used to result in some very odd looking code. Because of fact that heredocs are parsed ‘as is’, it means that you had to place all of the strings all the way to the left of the file. More modern versions of Ruby allow you to indent multiline strings so they can match the rest of the code styles.

Solution

Can be found on the solutions branch on github.

Jordan Hudgens

view all post
Leave a comment

Please be polite. We appreciate that.

By Daniele Zedda • 18 February

← PREV POST

By Daniele Zedda • 18 February

NEXT POST → 34
Share on