2017-05-05 42 views
2

我正在用Ecto做一個小型的Cli程序,當我查詢一些結果時,我得到一個列表,並在我學習Elixir的時候我無法在終端中正確執行格式化返回列表的函數的輸出。Elixir - 如何格式化Iex上列表的輸出

當我運行Repo.all(from u in Entry, select: u.title)我得到一個列表如下:

["test title", "second title"],我想格式化輸出到像:

***** 
test title 
***** 
second title 

列表中的每個項目的一個部門,但我不知道知道如何正確地做到這一點,或者這樣做的有效方式。我嘗試了列表推導,但是...它返回一個列表。試圖管道Enum.map/2IO.puts/1沒有結果,現在我需要一些幫助:-)

回答

2

我會使用Enum.map_join/3

iex(1)> ["test title", "second title"] |> 
...(1)> Enum.map_join("\n", &["*****\n", &1]) |> 
...(1)> IO.puts 
***** 
test title 
***** 
second title 
1

你可以試試這個

Repo.all(from u in Entry, select: u.title) |> 
Enum.reduce([], fn item, acc -> 
    ["********", item | acc] 
end) |> Enum.reverse |> Enum.join("\n") |> IO.puts 

或者更可重複使用的方法

iex(8)> display = fn list -> list |> Enum.reduce([], fn item, acc -> ["**********", item | acc] end) |> Enum.reverse |> Enum.join("\n") |> IO.puts end 
#Function<6.54118792/1 in :erl_eval.expr/5> 
iex(9)> ["test title", "second title"] |> display.()                 test title 
********** 
second title 
********** 
:ok 
iex(10)> ~w(one two three four) |> display.() 
one 
********** 
two 
********** 
three 
********** 
four 
********** 
:ok 
iex(11)> 

我經常使用的功能anoyn在iex中的方法。可以創建這樣的小功能,並重用它們而無需定義模塊。

在這裏,我將display函數添加到我的.iex.exs文件中。一個跑了它從一個全新的IEX會議

Interactive Elixir (1.4.2) - press Ctrl+C to exit (type h() ENTER for help) 
iex(1)> ~w(one two) |> display.() 
one 
********** 
two 
********** 
:ok 
iex(2)> 

編輯

如果你想要一個真正的通用的解決方案,你可以覆蓋IEX的檢查協議。但是,如果它在任何地方使用檢查,這可能會影響您的程序。

ex(7)> defimpl Inspect, for: List do 
...(7)> def inspect(list, _opt \\ []), do: Enum.map_join(list, "\n", &(["*******\n", &1])) 
...(7)> end 
warning: redefining module Inspect.List (current version defined in memory) 
    iex:7 

{:module, Inspect.List, 
<<70, 79, 82, 49, 0, 0, 7, 184, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 242, 
    131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 
    95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:__impl__, 1}} 
iex(8)> ["Test one", "Test two"] 
******* 
Test one 
******* 
Test two 
iex(9)>