Enumerable#all?
What does all? do?
all? returns true if every 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 every element is truthy (i.e., not nil or false).
The method short-circuits — it stops iterating as soon as it finds an element that fails the condition, making it efficient for large collections.
Basic Usage
With a block
[1, 2, 3].all? { |n| n > 0 } # => true
[1, 2, 3].all? { |n| n > 1 } # => false
The first example returns true because every number in [1, 2, 3] is greater than zero — the predicate holds for the entire collection. The second returns false because 1 fails the n > 1 check, and all? stops iterating immediately at that point. This short-circuit behavior is what makes all? efficient even on large collections where the first few elements are likely to fail.
Without a block
When called without a block, all? checks for truthy values. Only nil and false are falsy — everything else is truthy:
[1, 2, 3].all? # => true
[true, 1, "hello"].all? # => true
[true, false, 1].all? # => false
[false, nil].all? # => false
Without a block, all? checks truthiness: every element must be something other than nil or false. This is a quick way to verify that a collection contains no “missing” values — useful when you receive data from an external source and want to confirm that every field has been populated before processing.
Empty collections
An important edge case: all? returns true for empty collections. This is logically sound — an empty set vacuously satisfies any condition:
[].all? # => true
[].all? { |x| x > 5 } # => true
The true result for an empty collection follows from vacuous truth: there is no element that fails the condition, so the condition is trivially satisfied. This is logically consistent but can cause bugs when you assume an empty collection means “nothing to check” rather than “everything passed.” Always guard against empty input when the result of all? drives a conditional branch.
This behavior can be surprising, so always consider how your code handles empty input.
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].all?(Integer) # => true
[1, 2, "three", 4].all?(Integer) # => false
[1, 2, 3, 4].all?(String) # => false
["a", "b", "c"].all?(String) # => true
Passing a class or module as the argument to all? is syntactic sugar for checking Class === element on each item. This pattern form is especially concise for type validation — all?(Integer) reads like a type assertion on the entire collection. The === operator is what makes this work: for classes, Integer === 5 returns true, while Integer === "5" returns false.
This is equivalent to:
[1, 2, 3, 4].all? { |n| Integer === n } # => true
The block form and the pattern-argument form produce identical results because both rely on === under the hood. The pattern form is shorter and more declarative, while the block form gives you access to arbitrary logic — comparison operators, method calls, or compound conditions. Choose the pattern form for simple type checks and the block form when the condition involves multiple attributes or a computed value.
Practical examples
Validating all numbers meet a condition
scores = [85, 90, 78, 92, 88]
if scores.all? { |s| s >= 70 }
puts "All students passed!"
else
puts "Some students need improvement"
end
# => All students passed!
The scores example shows a typical validation pattern: iterate over a collection and check a numeric threshold. The if/else branch reads naturally because all? returns a boolean, making it a clean fit for conditional logic. When every element passes, you take the success path; otherwise, you handle the failure case.
Checking string constraints
usernames = ["alice", "bob", "charlie"]
usernames.all? { |name| name.length >= 3 } # => true
usernames.all? { |name| name.start_with?("a") } # => false
String constraints like minimum length or a required prefix are common uses of all? when validating user input. The second call returns false because not every username starts with "a" — only "alice" does. This Boolean return value makes all? well-suited for guard clauses that reject invalid input early in a method body.
Ensuring required keys are present
config = { timeout: 30, retries: 3, debug: false }
required_keys = [:timeout, :retries, :debug]
config.keys.all? { |key| required_keys.include?(key) } # => true
The required_keys check verifies that every key in the config hash belongs to a known set of allowed keys. This is a simple form of schema validation — it confirms that the configuration contains no unexpected fields, which helps catch typos and misconfigurations before they cause problems deeper in the application.
Type validation
def all_integers?(array)
array.all?(Integer)
end
all_integers?([1, 2, 3, 4]) # => true
all_integers?([1, 2, "three"]) # => false
The all_integers? helper wraps all?(Integer) in a named method, which makes the intent clearer at the call site. This is a pattern worth adopting when the same collection-wide check appears in multiple places — the method name documents what is being validated without the reader having to parse the all? block each time.
Short-circuit evaluation
all? stops as soon as it finds an element that fails the condition. This matters when the block has side effects or when performance is critical:
# Stops at the first failing element
[1, 2, 3, 4].all? do |n|
puts "Checking #{n}"
n < 3
end
# => false
# Output:
# Checking 1
# Checking 2
# Checking 3
The output demonstrates that all? stops as soon as it hits the first failing element. It checks 1, 2, and 3 — then stops because 3 < 3 is false. The fourth element (4) is never inspected. This early-exit behavior makes all? safe to use with blocks that have side effects like logging or metrics emission, because failed collections won’t trigger the block for every element.
Performance considerations
Lazy evaluation
Because all? short-circuits, the best case (first element fails) exits immediately, but the worst case (all elements pass) requires checking every element:
# Worst case: O(n) — all elements pass
[1, 2, 3].all? { |n| n < 10 } # => true, checks all 3
# Best case: O(1) — first element fails
[10, 20, 30].all? { |n| n < 5 } # => false, stops at first element
The short-circuit examples show the best and worst cases for all? on a small array, but the real performance question is what you are checking against, not just how many elements you have. The choice of data structure for the validation target has a much larger impact on overall runtime than the linear scan of the collection itself.
Arrays vs sets
For membership testing, all? over an array performs linear search. If you frequently check whether all elements match a value, consider using more targeted structures:
# Array: O(n) linear search
data = [1, 2, 3, 4, 5]
data.all? { |n| n.is_a?(Integer) } # => true
# More efficient for specific use cases
valid_statuses = Set.new([:active, :pending, :completed])
[data.all? { |item| valid_statuses.include?(item.status) }]
When you combine all? with a Set for membership checks, you trade the linear scan of Array#include? for the constant-time lookup of Set#include?. This matters when the collection being checked is large — checking 10,000 elements against a 1,000-item array of valid statuses would perform 10 million comparisons, while the same check against a Set would perform only 10,000 lookups.
Relationship to any? and none?
all? is the opposite of any? and complements none?:
| Method | Returns true when… |
|---|---|
all? | Every element satisfies the condition |
any? | At least one element satisfies the condition |
none? | No element satisfies the condition |
# all? vs any?
[1, 2, 3].all? { |n| n > 0 } # => true (all > 0)
[1, 2, 3].any? { |n| n > 2 } # => true (3 > 2)
# all? vs none?
[1, 2, 3].all? { |n| n > 5 } # => false (none > 5, but all? returns false)
[1, 2, 3].none? { |n| n > 5 } # => true (no element is > 5)
The table above summarizes how all?, any?, and none? partition the space of possible outcomes. When every element passes, all? is true and both any? and none? with negated conditions are also true. Understanding these relationships helps you choose the most readable form for each situation.
You can often choose between all? and none? based on readability:
# These are equivalent:
collection.all? { |x| x.valid? }
collection.none? { |x| !x.valid? }
The two lines above are logically equivalent but read differently. all? { |x| x.valid? } states a positive condition (“everything is valid”), while none? { |x| !x.valid? } states a double negative (“nothing is invalid”). The positive form is almost always clearer, especially when the predicate itself already contains a negation.
Edge cases
Mixed truthy/falsy values
[1, "hello", true, []].all? # => true (all truthy)
[1, "hello", false, []].all? # => false (false is falsy)
[1, "hello", nil, []].all? # => false (nil is falsy)
The mixed-collection examples highlight Ruby’s two falsy values: nil and false. Every other object — including 0, empty strings, empty arrays, and empty hashes — is truthy. This is different from languages like JavaScript or Python where 0 and empty collections are falsy, so Ruby developers coming from those languages should pay extra attention to all? without a block on numeric or container collections.
Special objects
Remember that false and nil are the only falsy values in Ruby. Everything else is truthy:
[0, "", [], {}].all? # => true (0, "", [], {} are all truthy)
See Also
- /reference/enumerable/enumerable-any/ — Returns true if any element satisfies the condition
- /reference/enumerable/enumerable-none/ — Returns true if no element satisfies the condition
- /reference/enumerable/enumerable-find/ — Returns the first element that satisfies a condition