> ## Content Index
> Fetch the complete content index at: https://www.modernlearner.org/llms.txt
> Use this file to discover other available public pages before exploring further.

# Multiline Strings in Ruby
- URL: https://www.modernlearner.org/multi-line-strings-in-ruby/
- Published: 2020-10-19T12:01:37.000Z
- Updated: 2024-04-09T22:10:33.000Z
- Description: Multiline strings in Ruby are easy to use with the HEREDOC syntax or the percent string syntax. Create multiple line strings with heredoc.
- Author: Modern Learner

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:

```ruby
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:

```ruby
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](https://www.modernlearner.org/product-analytics-introduction/) where you may have a query or sub-queries:

```ruby
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.

```ruby
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:

```ruby
multiline = <<~HELLO
  hello
    world
HELLO

# Output:
# hello
# world

```

# Multiline percent string in Ruby

You can also use a [percent string](https://ruby-doc.org/core-2.3.0/doc/syntax/literals%5Frdoc.html?ref=modernlearner.org#label-Percent+Strings) to create a multiline string using the `%q()` syntax:

```ruby
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.