Strings
Elixir has two kinds of strings: single-quoted and double-quoted. They differ significantly in their internal representation. But they also have many things in common. For example, see the following:
- Strings can hold characters in UTF-8 encoding.
- They may contain escape sequences:
`\a` BEL (0x07) `\e` ESC (0x1b) `\v` VT (0x0b) `\b` BS (0x08) `\f` FF (0x0c) `\s` SP (0x20) `\d` DEL (0x7f) `\n` NL (0x0a) `\t` TAB (0x09) `\r` CR (0x0d) `\xhh` 2 hex digits `\uhhh` 1–6 hex digits
- They allow interpolation on Elixir expressions using the syntax
#{...}
:iex> name = "dave" "Dave" iex> "Hello, #{String.capitalize name}!" "Hello, Dave!"
- Characters that would otherwise have special meaning can be escaped with a backslash.
- They support heredocs.
Heredocs
Any string can span several lines. To illustrate this, we’ll use both IO.puts
and IO.write
. We use write
for the multiline string because puts
always appends a newline, and we want to see the contents without this. Let’s look at the following code:
IO.puts "start"
IO.write "
my
string
"
IO.puts "end"
produces:
start
my
string
end
Notice how the multiline string retains the leading and trailing newlines and the leading spaces on the intermediate lines. The heredoc notation fixes this. If we triple the string delimiter ('''
or """
) and indent the trailing delimiter to the same margin as our string contents, we get the following:
IO.puts "start"
IO.write """
my
string
"""
IO.puts "end"
The code above produces the following:
start
my
string
end
Heredocs are used extensively to add documentation to functions and modules.
Get hands-on with 1400+ tech skills courses.