Multiline Strings in Ruby

The Ruby programming language lets you create variables that store strings that are plain, interpolated or multiline.

Multiline strings can be created in many ways. One of those ways is to use a double-quoted string:

puts "Hello,

World"

# Output:
# Hello,
# 
# World

Another way to create a multiline string is as HEREDOCs, which were inspired by the Perl programming language.

Here is how you can create a multiline string variable in Ruby with a HEREDOC:

sentence = 'hello world'.
interpolated = "#{sentence} #{sentence} another sentence added."
multiline = <<-TEXT
This is a string
  with multiple lines
The string used to start it,
Is also the string that ends it.
TEXT

more_multiline = <<-EOF
Hello
World
EOF

Multiline strings are very useful if you need to create complex SQL queries, such as for product analytics data where you may have a query or sub-queries:

query = <<-SQL
  SELECT user_id, SUM(engagement_score) as total_score
  FROM user_engagements
  WHERE engagement_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
  GROUP BY user_id
  HAVING total_score > 100
SQL

results = ActiveRecord::Base.connection.execute(query)

Multiline Syntax in Ruby

You can use the the syntax <<-TEXT to start a multiline string in Ruby. The "TEXT" part can be any other string. The multiline string will be defined as soon as that "TEXT" is encountered on another line.

multiline = <<-HELLO
  hello
    world
HELLO

# Output:
#   hello
#     world

Important: This will not strip out any whitespace at the beginning of each line.

Multiline Syntax in Ruby 2.3+

In Ruby 2.3+, you can use a ~ tilde instead of a - dash in the multiline syntax to strip out the whitespace at the beginning of each line:

multiline = <<~HELLO
  hello
    world
HELLO

# Output:
# hello
# world

Multiline percent string in Ruby

You can also use a percent string to create a multiline string using the %q() syntax:

multiline = %q(
  hello
    world
)

# Output:
#   hello
#     world

Important: This will not strip out any whitespace at the beginning of each line. It will preserve any tabs or spaces at the beginning of the line.