TLDR

  • Ruby has 6 ways to create strings, ', ", %q(), %Q(), %() and HEREDOCs.
  • Ruby strings have interpolation as well as escape sequences(\n, \t, etc) handling.
  • %Q/%/%q can use any character as delimiter e.g. (, {, etc.

How to use

  • Interpolation + escape sequences => "
  • Same as above but don't want to escape using \" => %Q()/%()
  • No Interpolation or escape sequences => '
  • Same as above but don't want to escape using \' => %q()
  • Multiline large text => HEREDOC. Always use <<~TAGNAME and make life easier.

Types of strings

Double quotes

  • Look like "A string".
  • Are interpolated.
a = 3
puts "a = #{a}" # => "a = 3"
  • escape sequences.
a = 3
b = "\n" # => \n is newline character
  • Need to escape " within them.
a = "This is a \"super\" string" # => This is a "super" string

%Q() and %()

  • Same as double quotes.
  • No need to escape ".
a = %(This is a "super" string) # => This is a "super" string
  • Can use any delimiter.
%{a} == %(a) == %[a]

Single quotes

  • No interpolation or escape sequences.
a = 3
puts 'a = #{a}\n' # => "a = #{a}\\n"
  • Need to escape ' within them.
a = 'This is a \'super\' string' # => This is a 'super' string

%q()

  • Just as %Q is to Double quotes, %q is to single quotes.
  • Same as single quotes.
  • No need to escape '.
a = %q(This is a 'super' string) # => This is a 'super' string
  • Can use any delimiter.
%q{a} == %q(a) == %q[a]

HEREDOC

  • A way to write multiline strings, or templates in another language.
  • Better way to write multiline strings as multiple options are provided.
  • Supports interpolation and escape sequences.
  • Basic usage
a = <<HEREDOC
This
is
a
multiline
string
HEREDOC
  • Start with <<{TAGNAME in uppercase}.
  • Start string on a newline.
  • End with <<{TAGNAME} on a newline.

<<-TAGNAME allows us to write the ending tag at any indentation.

def method
  a = <<-HEREDOC
This
is
a
multiline
string
      HEREDOC
end

<<~TAGNAME removes the starting whitespace from all lines equal to the lowest amount of starting whitespace on any line.

a = <<~HEREDOC
    A
  B
  C
    D
    HEREDOC
puts a # => "  A\nB\nC\n  D\n"

Summary

There you have it, the basics of using strings in ruby. Here's the link to the official String docs in case you're interested.