diff --git a/lib/elixir/lib/kernel.ex b/lib/elixir/lib/kernel.ex index bd6a4e62026..df942bb21df 100644 --- a/lib/elixir/lib/kernel.ex +++ b/lib/elixir/lib/kernel.ex @@ -3898,51 +3898,70 @@ defmodule Kernel do ## One-liner examples - if(foo, do: bar) + iex> if 7 > 5, do: "yes" + "yes" - In the example above, `bar` will be returned if `foo` evaluates to - a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be - returned. + iex> if "truthy value", do: "yes" + "yes" + + In the examples above, the `do` clause is evaluated and `"yes"` will be returned + because the condition evaluates to a truthy value (neither `false` nor `nil`). + Otherwise, the clause is not evaluated and `nil` will be returned: + + iex> if 3 > 5, do: "yes" + nil + + iex> if nil, do: IO.puts("this won't be printed") + nil An `else` option can be given to specify the opposite: - if(foo, do: bar, else: baz) + iex> if 3 > 5, do: "yes", else: "no" + "no" ## Blocks examples It's also possible to pass a block to the `if/2` macro. The first example above would be translated to: - if foo do - bar - end + iex> if 7 > 5 do + ...> "yes" + ...> end + "yes" - Note that `do`-`end` become delimiters. The second example would + Note that `do`-`end` become delimiters. The third example would translate to: - if foo do - bar - else - baz - end - - ## Examples - - iex> if 5 > 7 do - ...> "This will never be returned" + iex> if 3 > 5 do + ...> "yes" ...> else - ...> "This will be returned" + ...> "no" ...> end - "This will be returned" - - iex> if 2 + 2 == 4, do: :correct - :correct - - iex> if 2 + 2 == 5, do: :correct - nil + "no" If you find yourself nesting conditionals inside conditionals, consider using `cond/1`. + + ## Variables scope + + Variables set within `do`/`else` blocks do not leak to the outer context: + + x = 1 + if x > 0 do + x = x + 1 + IO.puts(x) # prints 2 + end + x # 1 + + Variables set in the condition are available in the outer context: + + fruits = %{oranges: 3} + if count = fruits[:apples] do + # won't be evaluated + IO.puts(count + 1) + end + count # nil + """ defmacro if(condition, clauses) do build_if(condition, clauses)