🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Pipe Operator

The pipe operator is the |> symbol, which passes a value as the first argument to the next function. A chain of pipes lets each step feed its result into the step below it.

A pipe sends text into upcase

The string on the left becomes the first argument of String.upcase. The result is the same text in capital letters.

result = "hello" |> String.upcase()

IO.puts(result)

A chain trims first and then upcases

The chain runs from top to bottom. The trim step removes the spaces, and the upcase step receives the trimmed text.

text =
  "  hello  "
  |> String.trim()
  |> String.upcase()

IO.puts(text)

A pipe can end in your own function

The add_mark function belongs to the Shout module. The pipe sends the upcased text into it as its first argument.

defmodule Shout do
  def add_mark(text), do: text <> "!"
end

result = "hi" |> String.upcase() |> Shout.add_mark()

IO.puts(result)

Example

defmodule Label do
  def wrap(text), do: "[#{text}]"
end

result =
  "  elixir  "
  |> String.trim()
  |> String.upcase()
  |> Label.wrap()

IO.puts(result)

name = "ana" |> String.upcase() |> Label.wrap()
IO.puts(name)

Key points

  • Pipe operator: the |> symbol that sends a value into a function call.
  • First argument: the piped value is inserted as the first argument of the next function.
  • Chain: several pipe steps run in order, each one receiving the result of the step above.
  • Reading order: a pipe chain reads from top to bottom, in the order the steps run.
  • Equivalence: "hi" |> String.upcase() means the same as String.upcase("hi").
  • Own functions: a pipe can send a value into a function from your own module.

In this example, the first chain trims the spaces, upcases the word, and wraps it in brackets with the Label module. The second chain runs the same last two steps on a name in a single line.

Note

in Elixir, the pipe changes how a call is written, not what the function does.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does "hi" |> String.upcase() return?