2017-03-29 9 views
0

パイプラインプレースホルダーを関数の第2引数にどのように渡すことが可能ですか?パイプラインとプレースホルダーの引数

defdefmodule CamelCase do 
    str = "The_Stealth_Warrior" 
    def to_camel_case(str) do 
    str 
    |> Regex(~r/_/, 'need_to_pass_str_argument_here', "") 
    |> String.split(" ") 
    |> Enum.map(&(String.capitalize(&1))) 
    |> List.to_string 
    end 
end 


ExUnit.start 

defmodule TestCamelCase do 
    use ExUnit.Case 
    import CamelCase, only: [to_camel_case: 1] 

    test "to_camel_case" do 
    assert to_camel_case("The_Stealth_Warrior") == "TheStealthWarrior" 
    end 
end 

# Error 
iex> 
    ** (FunctionClauseError) no function clause matching in Regex.replace/4 
    (elixir) lib/regex.ex:504: Regex.replace("The_Stealth_Warrior", ~r/\W/, " ", []) 
+0

あなたがしたいことがあれば、ビルトイン['Macro.camelize/1'](https://hexdocs.pm/elixir/Macro.html#camelize/1)を使うことができます – Sheharyar

+0

ねえ@Sheharyar、私はこれがElixirのパイプラインで練習するだけのものであることに同意します。 –

答えて

3

あなたは無名関数を使用することができ、パイプを使用して2番目の引数として文字列を渡す:

iex(1)> "The_Stealth_Warrior" |> (fn s -> Regex.replace(~r/_/, s, "") end).() 
"TheStealthWarrior" 

しかし、この特定のケースのために、あなたが最初の引数として文字列を受け入れる代わりにString.replace/3を使用することができます第二引数として正規表現:

iex(2)> "The_Stealth_Warrior" |> String.replace(~r/_/, "") 
"TheStealthWarrior" 

\W_と一致していないので、私は、デモの目的のためにそれを変更しました。)

+0

匿名関数の最後にありがとうございます。()はこの関数を呼び出すだけですか? –

+1

末尾の '。()'は無名関数が1つの引数で呼び出されます。値はパイプを介して渡されます。 – Dogbert

関連する問題