エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Elixirで進捗表示したい!

Posted at

はじめに

0. 準備

  • Elixirをインストールしましょう
  • 手前味噌の記事ですが、インストール等ご参考にしてください

ソースコードを書く

  • 今回はprogress.exsファイルをそのへんにつくるだけにします
progress.exs
f = fn
  n when is_integer(n) -> Process.sleep(n)
  s -> IO.write("\r[#{s}]")
end

1..50
|> Enum.map(&String.duplicate("#", &1))
|> Enum.intersperse(100)
|> Enum.each(&f.(&1))
  • fに束縛した無名関数は引数が整数の時にはProcess.sleep/1を実行してスリープします
  • 整数ではない場合にはIO.write/1を呼び出して出力をしています
  • 元の記事にありますように\rが出力する文字列の先頭にあることがポイントです
  • 1..50ではじまる行からは以下の関数や、Pipe operator |>を使って気持ちよく書いています
  • Enum.intersperse(100)を実行した時点で下記のようなリストができています
["#", 100, "##", 100, "###", 100, "####", 100, "#####", 100, "######", 100,
 "#######", 100, "########", 100, "#########", 100, "##########", 100,
 "###########", 100, "############", 100, "#############", 100,
 "##############", 100, "###############", 100, "################", 100,
 "#################", 100, "##################", 100, "###################",
 100, "####################", 100, "#####################", 100,
 "######################", 100, "#######################", 100,
 "########################", 100, "#########################", 100, ...]
  • 文字列と100が交互に入っているリストになっています
progress.exs
1..50
|> Enum.map(&String.duplicate("#", &1))
|> Enum.intersperse(100)
|> IO.inspect()
|> Enum.each(&f.(&1))
  • ってな感じで途中がどうなっているのかをIO.inspect/1で出力して確認するのはよくやることです

実行する

$ elixir progress.exs

output.gif

:tada::tada::tada:

Wrapping Up :lgtm: :qiita-fabicon: :lgtm:

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?