1
0

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.

整数のListを期待していたら文字列のようなものが返ってきた => それCharlistsかも!(Elixir)

Last updated at Posted at 2020-09-05

はじめに

Player |> Repo.all |> Enum.map(& &1.number)
みたいなコードの結果が'\t\b'になりました。これは何でしょうか?

答えはCharlistsでしょう

iex> [9, 8]
'\t\b'
  • ElixirはListの要素がすべて整数で、それぞれの整数がアスキー文字として印字可能なものであれば、シングルクォーテーション(')でくくられたアスキー文字の列で表示することになっています
  • いやいやそんなのやめてくれ、整数のリストで表示したいよという場合にはIExの設定を変えてあげるとよいです
  • 整数のリストで結果を確認したいときはIExの設定を変えてあげましょう
    • ~/.iex.exsに設定を予め書いておくこともできます
iex> IEx.configure(inspect: [charlists: :as_lists])
:ok

iex> [9, 8]
[9, 8]
  • h IEx.configureh Inspect.Optsでヘルプを表示すると設定の仕方が書いてあります

本当にそうなの?

$ mix phx.new hello --live
$ cd hello 
$ mix ecto.create
$ mix phx.gen.live Baseball Player players name:string number:integer
  • router.exの変更は、今回の例では必ずしも必要な手順ではありません
lib/hello_web/router.ex
  scope "/", HelloWeb do
    pipe_through :browser

    live "/", PageLive, :index

    live "/players", PlayerLive.Index, :index # add
    live "/players/new", PlayerLive.Index, :new # add
    live "/players/:id/edit", PlayerLive.Index, :edit # add

    live "/players/:id", PlayerLive.Show, :show # add
    live "/players/:id/show/edit", PlayerLive.Show, :edit # add
  end
priv/repo/seeds.exs
Hello.Repo.insert!(%Hello.Baseball.Player{name: "テッド・ウィリアムズ", number: 9})
Hello.Repo.insert!(%Hello.Baseball.Player{name: "原辰徳", number: 8})
$ mix ecto.migrate
$ mix run priv/repo/seeds.exs
$ iex -S mix
iex> alias Hello.Repo
Hello.Repo

iex> alias Hello.Baseball.Player
Hello.Baseball.Player

iex> Player |> Repo.all |> Enum.map(& &1.number)
[debug] QUERY OK source="players" db=8.4ms decode=1.6ms queue=0.8ms idle=1527.6ms
SELECT p0."id", p0."name", p0."number", p0."inserted_at", p0."updated_at" FROM "players" AS p0 []
'\t\b'
  • うん、やっぱりそうだね :lgtm:
iex> IEx.configure(inspect: [charlists: :as_lists])
:ok

iex> Player |> Repo.all |> Enum.map(& &1.number)   
[debug] QUERY OK source="players" db=2.6ms idle=1775.7ms
SELECT p0."id", p0."name", p0."number", p0."inserted_at", p0."updated_at" FROM "players" AS p0 []
[9, 8]

Wrapping Up :lgtm:

  • 整数のListを期待していたら文字列のようなものが返ってきた => それはCharlistsかもしれません(きっとそうでしょう)
  • Enjoy Elixir! :rocket:
  • Enjoy Phoenix! :rocket:
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?