Search code examples
elixir

Elixir: How to test multiple values in case condition?


Is there a shorter way to write this:

case testvalue do
  200 ->
    true
  404 ->
    true
  _ ->
    false
end

It returns true for 200 or 404 and false for everything else. It would be nice to write it with an OR condition but this leads to an error:

case testvalue do
  200 || 400 ->
    true
  _ ->
    false
end

Solution

  • There's no direct syntax for or in the middle of patterns but you can use a guard:

    case testvalue do
      n when n in [200, 400] ->
        true
      _ ->
        false
    end
    

    You can also use or in guards. This will work too but is more verbose:

    case testvalue do
      n when n == 200 or n == 400 ->
        true
      _ ->
        false
    end
    

    Both will run equally fast as in inside guards is converted into comparisons + or, as mentioned in the docs.