LoginSignup
11
0

More than 1 year has passed since last update.

簡単Elixirシリーズ ~ unless を理解しよう~

Posted at

簡単Elixirシリーズ

~ unless を理解しよう ~

この記事は「Elixir Advent Calendar 2022」9日目の記事です
東京にいるけどfukuokaexのYOSUKEです。

簡単 Elixirシリーズでは小ネタをサクッと書いていこう。というコンセプトで作っていきます。

今回は、制御構造でifなどは理解できるけど、unlessって何? を理解する。という小ネタ(そう、この記事はサクッとがコンセプトW)

unlessの前にifを理解しよう。

unlessを知る前にifを理解しよう。

ifは条件式の判定が「正しい(true)」場合にendまでの処理を実行する制御構造です。
条件式の結果が「誤り(false)」の場合は何も処理をしません。

iex> x = 7
7
iex> if x < 10 do
...> "small"
...> end
"small"

unlessを理解しよう。

unlessは条件式の判定がfalseの場合にendまでの処理を実行する制御構造です。
条件式の結果がtrueの場合は何も処理をしません。

iex> x=11
11
iex> unless x < 10 do
...>   "Big"
...> end
"Big"
iex(3)> x = 1           
1
iex(4)> unless x < 10 do
...(4)> "Big"           
...(4)> end             
nil

ちなみに、ifにもunlessにも else 構文があります。

iex(4)> x = 1
1
iex(5)> unless x < 10 do
...(5)> "Big"
...(5)> else
...(5)> "small"
...(5)> end
"small"

大雑把に言うと、ifの逆と覚えておけばOK?

11
0
1

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
11
0