Skip to main content

Ruby Multiline String: Formatting Guide

Discover how to format a Ruby multiline string for a clean, readable codebase. We’ll walk you through HEREDOCs, handling indentation, and key string methods, with clear examples and best practices to optimize your output!

Sebastián Jara
Sebastián Jara June 24, 2024
Ruby On Rails: Herdocs + Squish

HEREDOCs offer a powerful solution for handling long strings in Ruby, but they can lead to formatting issues. In this guide, we explain how to manage indentation and eliminate extra spaces in your output using methods like squish and strip.

What are HEREDOCs and why use them?

HEREDOCs are a Ruby feature that allows you to write multiple lines of strings that respect the maximum line length set in your project. These come in handy when managing large code blocks like SQL queries or HTML, keeping the format intact.

However, the output may not look as expected due to the preserved format, line breaks, and indentation. To address this issue, you can use the squish method with a HEREDOC to leave your output clean.

How HEREDOCs improve readability

When working on a project, respecting line length is an essential best practice. If you’re working with a block of code, you can split your method into multiple smaller methods to keep the lines short. However, when you’re working with a literal string that exceeds the maximum number of characters per line set in your project, using the backslash () can make the code hard to read, especially if you have SQL queries in your code.

This is where HEREDOCs come in handy.

HEREDOCs are a way to write multiline strings while keeping their format and indentation. They even support interpolation, making them a great tool to use for long SQL queries or HTML code. However, the traditional HEREDOC syntax can be challenging due to issues with leading whitespace and managing indentation.

Traditional HEREDOC syntax

query = <<-SQL
SELECT users.id, users.first_name, users.last_name
FROM users
WHERE users.age >= 18
SQL
# Output: " SELECT users.id, users.first_name, users.last_name\n FROM users\n WHERE users.age >= 18\n"

This example splits a long line into multiple shorter ones, and the linter won’t complain about line length. However, when you look at your terminal output or your app’s log, you’ll notice that this code is displayed in a different format. While all the other output is shown inline, this piece of code preserves all the new lines and spaces (at the beginning of each line).

Extra spaces can lead to parsing errors in Ruby when working with HEREDOCs, so it’s important to handle them properly.

Formatting Ruby multiline string methods

Here are some methods to enable your output to look polished:

  • Strip: Removes spaces and newlines at the start and end of the string.
  • Squish: Removes all whitespace and newlines within the string, delivering a neat, single-line result.
  • Squiggly HEREDOC: cleans leading spaces while keeping sub-level indents intact.

So, for instance, to solve the aforementioned problem, you can combine the HEREDOC with some string methods, such as strip. As was said, this removes the spaces and new lines at the beginning and end of the string, but not in between lines.

We share a demonstration below:

Using strip for cleaner output

query = <<-SQL.strip
SELECT users.id, users.first_name, users.last_name
FROM users
WHERE users.age >= 18
SQL
# Output: "SELECT users.id, users.first_name, users.last_name\n FROM users\n WHERE users.age >= 18"

This instance removes the spaces and new lines at the beginning and end of the string, but not in between lines. To remove the spaces and new lines in between lines, you can use the squish method, which removes all whitespace, including new lines and spaces.

Using squish for single-line output

Let’s use this to exemplify:

query = <<-SQL.squish
SELECT users.id, users.first_name, users.last_name
FROM users
WHERE users.age >= 18
SQL
# Output: "SELECT users.id, users.first_name, users.last_name FROM users WHERE users.age >= 18"

Ruby 2.3 introduced the squiggly HEREDOC, which uses a tilde (~) instead of a hyphen (-), like this: < < ~HEREDOC. The result is similar to the example that uses the regular HEREDOC followed by squish, except that it leaves a newline character at the end of the string. Adding a strip to this example will leave a single-line string. Supposing you have a query with sub-levels marked by spaces, the squiggly HEREDOC will preserve those spaces, so you will have to use the squish to output the string in a single line without those spaces.

And that’s it! You now have a clean ruby multiline string that respects the best practices and rules in your project. This fosters a clear and neat output in the terminal, logs, or any other output method you’re using.

Why format matters

Handling extra newlines and extra indentation is crucial for clean code output. Proper formatting prevents parsing errors and enables logs and terminals to display results as expected.

Best practices for Ruby multiline string formatting

To foster readability and maintainability in your project’s code, follow these key best practices:

  • Avoid clutter by using HEREDOCs with methods like strip and squish.
  • Use the squiggly HEREDOC for leading space control.
  • Preserve readability by respecting your project’s maximum line length.

Have you tried this before? Let us know your thoughts or comments!

Wrapping up

With HEREDOCs and the right methods, you can manage multiline strings in Ruby more efficiently. Clean output doesn’t just make logs easier to read—it actively prevents errors. These techniques foster readable, maintainable code while improving collaboration within teams.

Adopting best practices for string handling simplifies debugging and enhances performance, making your development process more efficient. It’s not just about keeping things tidy—clean code is scalable and adaptable.

Let’s simplify complexity—code should be powerful yet approachable.

Partnering for your growth

Image by Unsplash. Partnering for your growth

Our article on Ruby multiline strings highlights a crucial part of web and mobile development: maintaining clean, efficient code. By optimizing string handling and delivering clean output, we help improve your application’s performance and scalability.

Whether you’re managing complex backend systems or building fast, responsive apps, our expertise drives impactful results. See what our clients have to say! Read their reviews.

Let's build something
together!