How to assign a default value to a variable if the first condition fails?

I have the following expression in Ruby:

env = opts.env || "staging"

How to record it in Elixir?

EDIT:

This expression in Elixir will not 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> 
+5
source share
2 answers

Exactly the same idiom job (assuming "unsuccessfully" that you mean opts.env is zero):

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

An elixir, like Ruby, treats nil as a value of falsity.

+8
source

For completeness, this will 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" 
+1
source

Source: https://habr.com/ru/post/1242635/


All Articles