Elixir's version of the ternary operator

Essential Elixir : part 2 of 10 published on Aug 06, 2015

Say you have a simple if/else statement in Ruby.

if (state == "TX") 
  message = "Howdy World"
else
  message = "Hello World"
end

You could condense the code using the ternary operator.

message = state == "TX" ? "Howdy World" : "Hello World"

Elixir you don’t have a ternary operator, but you can still shorten the code.

We will start with an if/else statement.

if (state == "TX") do
  message = "Howdy World"
else
  message = "Hello World"
end

You can then condense that code to:

message = if (state == "TX"), do: "Howdy World", else: "Hello World"

So although there isn’t an explicit ternary operator, you can still achieve the same result but just using vanilla Elixir.

Next: Convert int to float and float to int with Elixir