Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

elixir - Why can't I chain String.replace?

I'm working on a price format function, which takes a float, and represent it properly.

ex. 190.5, should be 190,50

This is what i came up with

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

If i run the following.

format_price(299.0)
# -> 299,0

It looks like it only ran through the first replace. Now if i change this to the following.

  def format_price(price) do
    formatted = price
    |> to_string
    |> String.replace ".", ","

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

    formatted = formatted
    |> String.replace " ", ""
  end

Then everything seems to work just fine.

format_price(299.0)
# -> 299,00

Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...