Skip to content
Merged
Changes from 3 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
58 changes: 35 additions & 23 deletions lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3898,51 +3898,63 @@ 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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the example above, "yes" is returned because 7 > 5 evaluates to a truthy value (true in this case). nil will be returned if the condition evaluates to a falsy(nil or false) value:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @dmitrykleymenov, good catch!
Fixed in 96bbccf

a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be
returned.

iex> if 3 > 5, do: "yes"
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
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
IO.puts(count + 1)
end
count # nil

"""
defmacro if(condition, clauses) do
build_if(condition, clauses)
Expand Down
Loading