如果第一个条件失败,如何为变量赋值?

时间:2016-02-09 16:59:52

标签: elixir

我在Ruby中使用了表达式:

env = opts.env || "staging"

如何在Elixir中书写?

修改

Elixir中的这个表达式不起作用:

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

错误:

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

3 个答案:

答案 0 :(得分:11)

完全相同的成语(假设“失败”,你的意思是opts.env为零):

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

Elixir,作为Ruby,将零视为虚假价值。

答案 1 :(得分:1)

为了完整起见,这也可以做你想要的:

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"

答案 2 :(得分:0)

要在Elixir中添加有关structs的常规信息,

由于结构不允许访问不存在的键,因此您将面对KeyError。 虽然结构是建立在地图之上的。通过在结构上使用map函数,可以获得不存在的键的预期行为。

如果未为结构定义键,

Map.get(<struct>, <key>)将返回nil:

# 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"