TLDR
- Ruby has 6 ways to create strings,
'
,"
,%q()
,%Q()
,%()
andHEREDOCs
. - 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.
1 2
a = 3 puts "a = #{a}" # => "a = 3"
- escape sequences.
1 2
a = 3 b = "\n" # => \n is newline character
- Need to escape
"
within them.1
a = "This is a \"super\" string" # => This is a "super" string
%Q() and %()
- Same as double quotes.
- No need to escape
"
.1
a = %(This is a "super" string) # => This is a "super" string
- Can use any delimiter.
1
%{a} == %(a) == %[a]
Single quotes
- No interpolation or escape sequences.
1 2
a = 3 puts 'a = #{a}\n' # => "a = #{a}\\n"
- Need to escape
'
within them.1
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
'
.1
a = %q(This is a 'super' string) # => This is a 'super' string
- Can use any delimiter.
1
%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
1 2 3 4 5 6 7
a = <<HEREDOC This is a multiline string HEREDOC
- Start with
<<{TAGNAME in uppercase}
. - Start string on a newline.
- End with
<<{TAGNAME}
on a newline.
- Start with
<<-TAGNAME
allows us to write the ending tag at any indentation.1 2 3 4 5 6 7 8 9
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.1 2 3 4 5 6 7
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.