Why can’t I chain String.replace?

EDIT On the master branch of Elixir, the compiler will warn if a function is piped into without parentheses if there are arguments.


This is an issue of precedence that can be fixed with explicit brackets:

price
|> to_string
|> String.replace(".", ",")
|> String.replace(~r/,(\d)$/, ",\\1 0")
|> String.replace(" ", "")

Because function calls have a higher precedence than the |> operator your code is the same as:

price
|> to_string
|> String.replace(".",
  ("," |> String.replace ~r/,(\d)$/,
    (",\\1 0" |> String.replace " ", "")))

Which if we substitute the last clause:

price
|> to_string
|> String.replace(".",
  ("," |> String.replace ~r/,(\d)$/, ".\\10"))

And again:

price
|> to_string
|> String.replace(".", ",")

Should explain why you get that result.

Leave a Comment