How to define a multiline string in Ruby

Search for a command to run...

No comments yet. Be the first to comment.
PostgreSQL Upgrade and Database Restoration Guide To support the pgvector gem, I upgraded my local Postgres.app from v13 to v17 on macOS. Below is the full upgrade and restoration process for my project. Environment OS: macOS PostgreSQL: Upgraded f...

Introduction In Ruby on Rails applications, handling database transactions efficiently is crucial to maintaining data integrity. One common issue developers face is dealing with runtime errors caused by unpersisted changes when using the with_lock me...

Environment MacOS Sonoma 14.3 Original Ruby version: 2.7.8 Ruby Version Manager: RVM 1.29.12 Goal Upgrade Ruby from 2.7.8 to 3.0.6. Issues Description After successfully installing Ruby 3.0.6, I encountered difficulties running bundle install in...

It is common to see require 'something' in a Rails application. But what exactly does require do? What is require used for in Ruby? require is used to load external libraries or modules into your program. For example, Before you require the JSON modu...

In my daily job, I mainly use Rails framework. To make code readable and maintainable, we seldom write raw SQL in the codebase. Instead, we use Rails's ActiveRecord::QueryMethods module which helps developers write beautiful queries quickly. For exam...

Note: The following was tested with Ruby 2.6.6
Keyword: Heredoc
Heredoc is used for a form of multiline strings and preserves the line breaks and whitespace (including indentation) in the text.
string = <<~HEREDOC
How are you?
HEREDOC
Start with <<- or <<~.
The word HEREDOC can be replaced with any text, ex. SQL, HTMLetc.
End with the word you have defined, ex. HEREDOC.
It's simple.
string = <<~HEREDOC
How are you, #{User.first.name}?
HEREDOC
#=> "How are you, Lynn\n"
If you would like to disable the interpolation, you can put the single quotes around the heredoc name.
string = <<~'HEREDOC'
How are you, #{User.first.name}?
HEREDOC
#=> "How are you, \#{User.first.name}?\n"
<<- and <<~?<<-
string = <<-HEREDOC
Today is a nice day.
HEREDOC
#=> " Today is a nice day.\n"
<<~
string = <<~HEREDOC
Today is a nice day.
HEREDOC
#=> "Today is a nice day.\n"
<<- will maintain the original indentation. Ruby 2.3 introduced the squiggly heredoc <<~ which can removes extra indentation.
You might notice that there is a newline character \n at the end of the return value. If you would like to remove an extra newline, strip will be useful.
string = <<~HEREDOC.strip
Today is a nice day.
HEREDOC
#=> "Today is a nice day."