leon
leon

Reputation: 441

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

I've in Ruby following expression:

env = opts.env || "staging"

How to write it in Elixir?

EDIT:

This expression in Elixir won't work:

case Repo.insert(changeset) do
  {:ok, opts} ->
    env = opts.env || "staging"

Error:

** (KeyError) key :env not found in: %Myapp.App{__meta__: #Ecto.Schema.Metadata<:loaded>

Upvotes: 9

Views: 8319

Answers (3)

Cwt
Cwt

Reputation: 8566

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"

Upvotes: 2

Onorio Catenacci
Onorio Catenacci

Reputation: 15293

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"

Upvotes: 1

Paweł Obrok
Paweł Obrok

Reputation: 23164

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.

Upvotes: 21

Related Questions