How to return one value from ETS in Elixir?

i have ETS table that have key values scheme like this:

users = :ets.tab2list(:users)
IO.inspect users # printing

 name: "John",
 id: "3eadd68495d",
 status: "Free"
 name: "Steve",
 id: "234a34495d",
 status: "Free"
 name: "Mike",
 id: "9add68495d",
 status: "Busy"

And I want to get one id of any element, that have status "Free".

I'm already tried to get value using loop

users = :ets.tab2list(:users)
for user <- users do
   userValue = user |> elem(1)
   if userValue.status === "Free" do

but it returns multiple id values (3eadd68495d234a34495d), not one

i need smth like "break" after if userValue.status === "Free" do but i have no idea how to use this in Elixir.


  • For the single value, one should use Enum.reduce_while/3.

    Enum.reduce_while(users, nil, fn
      {_, %UserType{status: "Free", id: id}}, _ -> {:halt, id}
      _, acc -> {:cont, acc}

    or as pointed out by @sabiwara in comments, use Enum.find_value/2.

    I would not recommend this, but one might do try/catch to “break” the for comprehension as shown below.

    try do
      for {_, %UserType{status: "Free", id: id}} <- users, do: throw(id)
      id -> id

    Sidenote: generally speaking, it is extremely inefficient and once you already have ETS, you’d better be using as described in

    Somewhat alongside the following lines should do
      [{{:_, %{status: :"$1", id: :"$2"}},
       [{:"==", :"$1", "Free"}],