Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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>
like image 442
leon Avatar asked Feb 09 '16 16:02

leon


People also ask

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

What is the default value of object variable * undefined?

undefined is a type by itself (undefined). Unassigned variables are initialized by JavaScript with a default value of undefined. Here as the variable is declared but not assigned to any value, the variable by default is assigned a value of undefined. On the other hand, null is an object.


1 Answers

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.

like image 136
Paweł Obrok Avatar answered Oct 05 '22 15:10

Paweł Obrok