Ruby enumerable: find/any/all
This course looks at Ruby's any?, all? and none? called without a block, where each element is judged by its own truthiness. It also covers the pattern-argument form added in Ruby 2.5, which checks each element with ===. It explains vacuous truth, the reason an empty array returns true for all? and false for any?. A trace shows find stopping at the first match, while select.first checks every element. The last methods are min_by and max_by, which return the element with the highest or lowest computed value.
What you'll learn
- ✓How any?, all? and none? judge truthiness when called without a block
- ✓The Ruby 2.5 pattern-argument form and its use of ===
- ✓Why empty collections make all? true and any? false
- ✓How a trace shows find stopping at the first match
- ✓Why select.first checks every element while find can stop early
- ✓Using min_by and max_by, including the top-n form
any?, all?, none? without a block
The lesson "Related Enumerable methods", in the intern course Ruby enumerable: select, showed any?, all? and none? running with a block: numbers.any? { |n| n > 4 }, numbers.all? { |n| n > 0 }, numbers.none? { |n| n > 10 }. It also covered count and find. None of that is repeated here. This course…
Read the full lesson free →Curriculum
7 lessonsany?, all?, none? without a block
Without a block, any?, all? and none? check each element's truthiness, where only nil and false are falsy.
The pattern-argument form (Ruby 2.5+)
Since Ruby 2.5, these methods accept one argument and check it with ===, so classes, ranges and regexes work.
Vacuous truth: when empty collections surprise you
Empty collections make all? and none? return true and any? return false, which calling code should handle on purpose.
find stops: a traced proof
A puts inside the block shows find checking four of ten elements, while select.first checks all ten.
find vs select.first: the real comparison
Both return the same value, but select builds the full list first, so find does less work when checks are costly.
min_by and max_by: new siblings
min_by and max_by return the element with the lowest or highest block value, and nil on empty collections.
Putting it together: sharper questions about collections
A review of the no-block and pattern forms, vacuous truth, find tracing and min_by, with an exercise combining select and min_by.