How to assign default value to variable if first condition failed?

For sake of completeness this would also do what you want:

e = "production" # Setting this only because I don't have an opts.env in my app.

env = if !e, do: "staging", else: e
#"production"

e = nil

env = if !e, do: "staging", else: e
#"staging"

To add general information regarding structs in Elixir:

As structs do not allow accessing noexistent keys, you are facing the KeyError. Though structs are built on top of maps. By using map functions on structs you can get the expected behavior for nonexistent keys.

Map.get(<struct>, <key>) will return nil if the key is not defined for the struct:

# With "opts" being a struct without "env" key

iex> Map.get(opts, :env) || "staging"
"staging"

# Map.get/3 has the same behavior
iex> Map.get(opts, :env, "staging")
"staging"

The exact same idiom works (assuming by "failed" you mean opts.env is nil):

iex(1)> nil || "staging"
"staging"
iex(2)> "production" || "staging"
"production"

Elixir, as Ruby, treats nil as a falsy value.

Tags:

Elixir