rubyguides

Enumerable#any?

What does any? do?

any? returns true if at least one element in the collection satisfies the given condition. If a block is provided, it tests each element against the block’s condition. If no block is given, it checks whether any element is truthy.

The method short-circuits — it stops iterating as soon as it finds a matching element, making it efficient for large collections.

That short-circuit behavior is why any? shows up so often in Ruby standard-library code and application code alike. It answers a simple yes-or-no question quickly, without asking the caller to inspect every element when the first match is already enough.

Basic Usage

With a block

[1, 2, 3].any? { |n| n > 2 }   # => true
[1, 2, 3].any? { |n| n > 5 }   # => false

Without a block

When called without a block, any? checks for truthy values. Only nil and false are falsy — everything else is truthy. This is a core Ruby convention that distinguishes the method from a simple size check: you can use it to ask whether a collection has any non-nil, non-false content without writing an explicit block.

[1, 2, 3].any?                 # => true
[false, nil, 1].any?           # => true
[false, nil].any?              # => false
[].any?                        # => false

The result for [false, nil] is especially worth remembering. Both false and nil are falsy, so the method reports that no element passes — which matches the intuitive reading of “is anything in here meaningful?” An empty collection also returns false because there are no elements to check, making the no-argument form a quick way to verify that a collection has at least one element with a usable value.

With a predicate argument

You can pass a pattern object as an argument. The method treats it like a block that calls === on the pattern:

[1, 2, 3, 4].any?(Integer)        # => true
[1, 2, 3, 4].any?(String)         # => false
["a", "b", "c"].any?(/b/)         # => true
["a", "b", "c"].any?(/x/)         # => false

The predicate form calls === on the argument for each element. For a class like Integer, Integer === n checks whether n is an instance of that class — so any?(Integer) returns true when any element is an integer. For a regex like /b/, === tests for a match, making any?(/b/) a shorthand for “does any element contain b?” without typing a block. The same pattern works with ranges, lambdas, and any object that implements ===.

The following version is equivalent to the class-check example above:

[1, 2, 3, 4].any? { |n| Integer === n }  # => true

The predicate form is useful when you already have a class or pattern that describes the match. It keeps the rule compact, and the call still reads like a direct question about the collection. Because the matching logic lives in the argument’s === method, you can reuse the same predicate across multiple calls without rewriting the condition each time.

Practical Examples

Checking if any number meets a condition

temperatures = [12, 15, 8, 22, 19]

if temperatures.any? { |t| t > 30 }
  puts "Warning: High temperature detected!"
else
  puts "All temperatures within safe range"
end
# => All temperatures within safe range

The temperature check shows how any? plugs into a conditional branch without tracking a separate boolean variable. The method handles the iteration and early exit, so the surrounding code reads as a simple yes-or-no question. That keeps the branching logic cleaner than a manual loop with an accumulator flag.

Checking for a matching string

users = ["alice", "bob", "charlie"]

users.any? { |name| name.start_with?("a") }   # => true
users.any? { |name| name.start_with?("z") }   # => false

Matching strings by prefix is a common pattern in user-facing code, and any? keeps the intent clear without pulling in a separate filter step. The block stays small because the method only needs to find one match — it does not collect results or count occurrences.

Checking if any elements exist

def process_queue(queue)
  return unless queue.any?
  # process items...
end

process_queue([])    # => nil (early return)
process_queue([1])   # => continues

This pattern is common when you only want to enter a branch if work is available. The any? call makes that guard easy to read and avoids a second pass over the array. Because the method short-circuits on the first truthy element, it also means the guard does not walk the entire collection when work is available — a nice performance property for large queues.

Validating input

def has_required_role?(user_roles, required_role)
  user_roles.any? { |role| role == required_role }
end

has_required_role?([:read, :write], :admin)    # => false
has_required_role?([:read, :admin], :admin)    # => true

The method works well for validation because it expresses the intent plainly: does at least one value meet the requirement? That question is often easier to follow than a longer loop with a manually tracked boolean. When the role list is long, the early exit also saves time — the check stops as soon as a match appears rather than scanning the entire list.

Short-Circuit Behavior

any? stops as soon as it finds a truthy result. This matters when the block has side effects or when performance is critical:

# Stops after finding the first match
[1, 2, 3, 4].any? do |n|
  puts "Checking #{n}"  # This prints only for 1 and 2
  n > 1
end
# => true
# Output:
# Checking 1
# Checking 2

The output confirms that the method exits after the second element, which is the first one where n > 1 returns true. The third and fourth elements are never inspected. This behavior is especially valuable when the block itself is expensive — a database query, a network call, or a complex computation — because you only pay for the work until the first match.

Empty collections

any? always returns false for an empty collection, regardless of the block:

[].any? { |x| x > 5 }   # => false
[].any?                  # => false

An empty collection has no matching element by definition, so the method stays predictable even when no data is present. This property is sometimes called “vacuous truth” in logic: the statement “at least one element satisfies the condition” is false for an empty set because there are no elements to satisfy it. Ruby follows that reading consistently for any?.

Performance Considerations

Lazy evaluation

Because any? short-circuits, the worst case (no element matches) requires checking every element, but the best case (first element matches) exits immediately:

# Worst case: O(n)
[1, 2, 3].any? { |n| n > 100 }  # => false, checks all 3

# Best case: O(1)
[100, 200, 300].any? { |n| n > 50 }  # => true, stops at first element

The worst case still scans the full collection, but the short-circuit makes the average case much better when matches tend to appear early. For a collection where most elements satisfy the condition, any? behaves like a constant-time check regardless of size. That makes it safe to use on large arrays in conditional guards where the match is expected to be found quickly.

Arrays vs Sets

For membership testing, any? over an array performs linear search. If you frequently check whether any element matches a value, consider a Hash or Set:

require "set"

tags = Set.new(["ruby", "rails", "web"])

# Array: O(n) linear search each time
languages = ["ruby", "python", "go"]
languages.any? { |lang| lang == "ruby" }  # => true

# Set: O(1) lookup
tags.any? { |tag| tag == "ruby" }  # => true

For repeated membership checks, a set often reads better than a loop because the lookup intent is explicit. any? still works, but the surrounding code should make it clear whether you are checking existence once or scanning a larger collection. If the same check runs many times against different values, switching to a data structure with O(1) membership testing usually pays off more than optimizing the any? call itself. The key insight is that any? answers “does at least one match?” while a set answers “is this specific value present?” — different questions with different performance characteristics. When you find yourself using any? with a simple equality check inside the block, consider whether the collection should be a set instead.

Relationship to all? and none?

any? is the complement of none? and the opposite of all?:

MethodReturns true when…
any?At least one element satisfies the condition
all?Every element satisfies the condition
none?No element satisfies the condition
# any? vs all?
[1, 2, 3].any? { |n| n > 2 }    # => true  (3 > 2)
[1, 2, 3].all? { |n| n > 2 }    # => false (1 > 2 and 2 > 2 are false)

# any? vs none?
[1, 2, 3].any? { |n| n > 5 }    # => false
[1, 2, 3].none? { |n| n > 5 }  # => true   (no element is > 5)

You can often choose between any? and none? based on readability:

The choice often comes down to how the question reads in the surrounding code — if the condition is stated positively, any? usually feels more natural, while none? pairs well with a negated condition.

# These are equivalent:
collection.any? { |x| x.nil? }
collection.none? { |x| !x.nil? }

See Also