Reason #121 • May 1st, 2026

Querying collections with #any? and friends

The Enumerable module provides many useful methods for querying collections. One such set is the predicate methods: any?, all?, none?, and one?. They allow you to check if any, all, none, or exactly one element in a collection satisfies a given condition:

Ruby
numbers = [1, 2, 3, 4, 5]

numbers.any? # => true
numbers.any?(Integer) # => true
numbers.any?(String) # => false
numbers.any? { |n| n > 3 } # => true
numbers.any? { |n| n > 5 } # => false
[].any? # => false

numbers.none? # => false
numbers.none?(String) # => true
numbers.none? { |n| n > 5 } # => true
[nil, false].none? # => true
[].none? # => true

numbers.one? # => false
["hello"].one? # => true
["hello", 108].one?(String) # => true

numbers.all?(Integer) # => true
numbers.all?(&:even?) # => false
[2, 4, 6].all?(&:even?) # => true
%w[two words].all?(/wo/) # => true

[nil, false].all? # => false
      
JavaScript
const numbers = [1, 2, 3, 4, 5];

const isString = x => typeof x === "string";
const isEven = x => x % 2 === 0;

numbers.some(Boolean); // true
numbers.some(Number.isInteger); // true
numbers.some(isString); // false
numbers.some(n => n > 3); // true
numbers.some(n => n > 5); // false
[].some(Boolean); // false

!numbers.some(Boolean); // false
!numbers.some(isString);// true
!numbers.some(n => n > 5);// true
![null, false].some(Boolean); // true
![].some(Boolean);// true

numbers.filter(Boolean).length === 1; // false
["hello"].filter(Boolean).length === 1; // true
["hello", 108].filter(isString).length === 1; // true

numbers.every(Number.isInteger); // true
numbers.every(isEven);// false
[2, 4, 6].every(isEven);// true
["two", "words"].every(s => /wo/.test(s)); // true
      

As you can see, there are three ways to use these methods: without arguments, with an object, or with a block. The first form checks if any/all/none/one element is truthy. The second form checks if an element matches the given object (by invoking === on it). The third form checks if elements satisfy the condition defined in the block.

History

Enumerable#all? and Enumerable#any? were the first of these methods to arrive. They were added to Ruby in March 2001, during the development that eventually led to Ruby 1.8.0. At first they were block-oriented methods, but in January 2003 Matz changed them to work without a block as well, giving us the truthiness form shown above. That behavior shipped in Ruby 1.8.0, released in August 2003.

Enumerable#one? and Enumerable#none? came a bit later in Ruby 1.8.7, released in 2008.

The pattern argument form is newer still. Ruby 2.5.0, released in December 2017, changed all four methods to accept an object and test each element with pattern === element. This is what makes examples like numbers.any?(Integer) and %w[two words].all?(/wo/) work without writing an explicit block.

Reason #122 ?