为什么不能链接String.replace? [英] Why can't I chain String.replace?

查看:86
本文介绍了为什么不能链接String.replace?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一种价格格式功能,该功能需要一个浮点数并正确表示它。

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

例如。 190.5,应该是190,50

ex. 190.5, should be 190,50

这就是我想出的内容

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

如果我运行以下命令。

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

为什么?

推荐答案

编辑在Elixir的master分支上,如果有参数,则将函数插入没有括号的编译器将发出警告。

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 " ", "")))

如果我们替换最后一个子句,则: / p>

Which if we substitute the last clause:

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

再次:

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

应解释为什么会得到该结果。

Should explain why you get that result.

这篇关于为什么不能链接String.replace?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆