65

How to do the similar conditional one-line check in Elixir?

if (x > 0) ? x : nil

Is this the only equivalent in elixir world?

if true, do: 1, else: 2

5 Answers 5

87

To me, the if IS the equivalent of a ternary operator as it evaluates to a value which for various other languages it doesn't.

so x = if false, do: 1, else: 2

is basically x = false? 1 : 2

Not sure why Ruby adopted it ( if you are coming from Ruby ) as it has assignable if statements. in C the ternary is useful as the code bloats with the equivalent if statements. Of course C programmers desperate for terseness went nuts and did many nested upon nested ternaries :)

0
36

Yes, there's nothing like a ternary operator in Elixir. The keyword version of if is probably the closest thing:

if condition, do: true_expr, else: false_expr
0
23

I saw this alternative in an tweet,

is_it_true && "TRUE" || "FALSE"
3
  • 17
    Note that this has a major gotcha: is_it_true && false || :foobar will always return :foobar and never false. This is because x && false will always evaluate to a falsy value, for any value of x – and false || x will always evaluate to x, for any value of x. The same gotcha applies if you have nil instead of false.
    – Henrik N
    Jun 25, 2016 at 21:41
  • 3
    a = true && 1 || 2, I don't see the gotcha here if you structure it well.
    – Besto
    Dec 10, 2017 at 4:53
  • 3
    a = argument_received && argument || default_value If you did receive the argument, but it happens to be a falsie, your program will ignore it, and that's probably not what you want, so... definitively there is a gotcha. Feb 15, 2021 at 22:51
2

An unmentioned and more verbose alternative is

case condition do true -> true_expr; _ -> false_expr end
1
  • That will get formatted to use 4 lines and lose truthiness/falseness
    – Nato Boram
    Jan 12, 2022 at 17:50
2
def ternary(condition, true_val, false_val) do
  if(condition, do: true_val, else: false_val)
end

so then

ternary(a < b, :ok, :error)
1
  • Nice, this looks much easier to read. Oct 19 at 22:42

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.