ryanbillingsley
ryanbillingsley

Reputation: 215

Access value in condition statement in Elixir

Is it possible to access the value that is the result of a condition? For instance:

cond do
    Map.get(values, :foo) ->
        IO.puts "Value: #{foo}"
    true ->
        IO.puts "No value"
end

Upvotes: 1

Views: 882

Answers (2)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

You could also try case like:

case Map.get(map, :key) do
  nil ->
    IO.puts "No value"

  value ->
    IO.puts "Value: #{inspect value}"
end

Please check this link if you want to learn more.

EDIT

This unfortunately is not accurate enough, as value related to :key might actually by nil. If you want to be sure if the value exists in mapand only then use it, you could try Map.fetch/2:

map = %{key: nil}

case Map.fetch(map, :key) do
  {:ok, value} ->
    IO.puts "Value: #{inspect value}"

  :error ->
    IO.puts "No value"
end

Upvotes: 3

Justin Wood
Justin Wood

Reputation: 10041

I think you want something like this.

cond do
  value = Map.get(map, :key) ->
    IO.puts "Value: #{inspect value}"
  true ->
    IO.puts "No value"
end

You will need to actually assign the value in order to use it.

Upvotes: 1

Related Questions