Ignoring a Value with _ (Underscore)

If we didn’t need to capture a value during the match, we could use the special variable _ (an underscore). This acts like a variable but immediately discards any value given to it—in a pattern match, it is like a wildcard saying, “I’ll accept any value here.” The following example matches any three-element list that has a 1 as its first element.

 
iex>​ [1, _, _] = [1, 2, 3]
 
[1, 2, 3]​​
 
iex>​ [1, _, _] = [1, ​"cat"​, ​"dog"​]
 
[1, ​"cat"​, ​"dog"​]

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.