Multi line iex

How do you enter multiple expressions in single iex line? x = 1 then y = 2 then x + y

I start with a round bracket ( then paste a multi-line expression, and close the round bracket ).

5 Likes

Pipes are especially tricky for this; pasting this into iex won’t work:

[1,2,3]
|> Enum.map(& &1 * 2)
|> Enum.join(" ")

since the first line will be evaluated immediately. I usually use a trick from Javascript to delay evaluation:

fn ->
[1,2,3]
|> Enum.map(& &1 * 2)
|> Enum.join(" ")
end.()
3 Likes

I like the parens/multiline approach, and I think that’s the right answer, but another available option is the semicolon:

iex> x = 1; y = 2; x + y
3
iex> x
1
iex> y
2
4 Likes

You can also paste that:

[1,2,3] \
|> Enum.map(& &1 * 2) \
|> Enum.join(" ")

Although I think using parentheses is the simple way.

This will work:

[1,2,3] |>
Enum.map(& &1 * 2) |>
Enum.join(" ")

True, but if I’m pasting code into IEx from sources that have been formatted with mix format it’s going to be in the "leading |>" form not the "trailing |>" one