Simulate ternary operator in Elixir

ElixirConditional Operator

Elixir Problem Overview


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

Elixir Solutions


Solution 1 - Elixir

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 :)

Solution 2 - Elixir

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

Solution 3 - Elixir

I saw this alternative in an tweet,

is_it_true && "TRUE" || "FALSE"

Solution 4 - Elixir

An unmentioned and more verbose alternative is

case condition do true -> true_expr; _ -> false_expr end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeo Choong PingView Question on Stackoverflow
Solution 1 - ElixirKeith NicholasView Answer on Stackoverflow
Solution 2 - ElixirmichalmuskalaView Answer on Stackoverflow
Solution 3 - ElixircoderVishalView Answer on Stackoverflow
Solution 4 - ElixirEthan ChenView Answer on Stackoverflow