Filtering with `for`
  •  1 min read

Filters for comprehensions work similar to guards on functions. If the result of the filter expression is false (or nil) the value is discarded.

# 1. Enumerate the numbers 1 through 6.
# 2. Only keep the numbers that are divisible by 2.
# 3. Multiply those numbers by 2.
for num <- [1, 2, 3, 4, 5, 6], rem(num, 2) == 0 do
  num * 2
end

# [4, 8, 12]

Multiple filters can be given to a single comprehension.

# 1. Enumerate through the list of names.
# 2. Only keep names that end with 'Baggins'.
# 3. Only keep the names that start with 'F'.
for name <- ["Frodo Baggins", "Bilbo Baggins", "Gandalf", "Faramir"],
    String.ends_with?(name, "Baggins"),
    String.starts_with?(name, "F") do
  name
end

# ["Frodo Baggins"]