0
0
Rubyprogramming~5 mins

Any?, all?, none? predicates in Ruby

Choose your learning style9 modes available
Introduction

These predicates help you check if some, all, or none of the items in a list meet a condition. They make it easy to answer questions like "Is any item true?" or "Are all items true?"

Checking if any student passed an exam in a list of scores.
Verifying if all tasks in a to-do list are completed.
Confirming that none of the emails in a list are invalid.
Finding out if any product in a shopping cart is on sale.
Ensuring all numbers in a list are positive before calculation.
Syntax
Ruby
array.any? { |item| condition }
array.all? { |item| condition }
array.none? { |item| condition }

These methods take a block with a condition to test each item.

They return true or false depending on the check.

Examples
Checks if any number is greater than 2. Here, 3 is greater, so it returns true.
Ruby
[1, 2, 3].any? { |n| n > 2 } # => true
Checks if all numbers are greater than 0. All are, so it returns true.
Ruby
[1, 2, 3].all? { |n| n > 0 } # => true
Checks if no numbers are less than 0. None are, so it returns true.
Ruby
[1, 2, 3].none? { |n| n < 0 } # => true
Checks if no numbers equal 2. Since 2 is present, it returns false.
Ruby
[1, 2, 3].none? { |n| n == 2 } # => false
Sample Program

This program checks three things about the numbers array using any?, all?, and none?. It prints true or false for each check.

Ruby
numbers = [5, 10, 15, 20]

puts "Any number > 18? #{numbers.any? { |n| n > 18 }}"
puts "All numbers > 3? #{numbers.all? { |n| n > 3 }}"
puts "None are zero? #{numbers.none? { |n| n == 0 }}"
OutputSuccess
Important Notes

If you call these methods without a block, they check if any, all, or none of the items are truthy or falsy.

These methods stop checking as soon as the answer is clear, so they are efficient.

Summary

any? returns true if at least one item meets the condition.

all? returns true only if every item meets the condition.

none? returns true if no items meet the condition.