Line break at the end of a multiline string

I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir

iex(2)> """
...(2)> asdf
...(2)> """
"asdf\n"

I wonder how I would create a multiline string without a trailing line break with elixir.

In swift I can add a line break by adding a newline

let lineBreaks = """
 
This string starts with a line break.
It also ends with a line break.
 
"""

which is the same as

line_breaks = """

This string starts with a line break.
It also ends with a line break.
"""

in elixir.

I feel like swift’s way is a bit more consistent and gives freedom to chose how to end the string.

Is there a reason for elixir’s multiline string to be different? I see only one advantage to this approach:

ab = """
a
b
"""

c = """
c
"""

ab <> c == """
a
b
c
"""

In swift it would be

"""
a
bc
"""

but can be fixed by adding a new line at the end of ab.

3 Likes
"""
Foo"""

# or even

"""Foo"""

I prefer the elixir behaviour over the swift one, as elixir complies with POSIX that text files should always end in a newline.

2 Likes

Uh, if Elixir worked that way I’d be fine with it, but it doesn’t, and based on the way Elixir’s does work I’d prefer Swift’s way as well:

╰─➤  iex
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:6:6] [ds:6:6:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> """
...(1)> Foo"""
** (SyntaxError) iex:2: invalid location for heredoc terminator, please escape token or move it to its own line: """

iex(1)> """Foo"""
** (SyntaxError) iex:1: heredoc start must be followed by a new line after """

the heck forum syntax coloring borked ^.^;

1 Like
iex(7)> """
...(7)> foo\
...(7)> """
"foo"
17 Likes

Hmmm? Did they remove this syntax? I think I used it in some old code… Perhaps I’m misremembering things though…

1 Like

I remember a PR about strengthening the messages when it was mis-used, but I don’t actually remember if it was valid at one point or not? I’m kind of thinking it was too, but that could easily be another language I’m thinking about. ^.^;

1 Like

In case someone stumbles on this thread: the “\” at the end to avoid newline still appears to work with recent versions of Elixir.

iex(1)> """
...(1)> foo\
...(1)> """
"foo"
iex(2)> """
...(2)> foo
...(2)> """
"foo\n"
2 Likes
"""
foo
"""
|> String.trim_trailing("\n")

Is clearer than mysterious backslashes IMO :slight_smile:

It’s subtly different though, because it will trim all trailing newlines, not just a single character.

If you only want to remove the last newline:

|> String.replace_suffix("\n", "")