Skip to content
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 46 additions & 27 deletions lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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 can be defined or rebound in `do`/`else` blocks, but these will not leak to the outer context:

x = 1
if x > 0 do
x = x + 1
IO.puts(x) # prints 2
end
x # 1

Variables can be defined in the condition as well, but they 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)
Expand Down
Loading