Array.any? / all? / none? / count
Methods for checking whether array elements satisfy a condition, and for counting elements that match a condition.
Syntax
# Returns true if at least one element satisfies the condition.
array.any? { |element| condition }
array.any? # Returns true if the array has at least one element
# Returns true if all elements satisfy the condition.
array.all? { |element| condition }
array.all? # Returns true if no element is nil or false
# Returns true if no element satisfies the condition.
array.none? { |element| condition }
# Returns the number of elements matching the condition.
array.count
array.count(value)
array.count { |element| condition }
Method List
| Method | Description |
|---|---|
| any? | With a block, returns true if at least one element satisfies the condition. Without a block, returns true if the array is not empty. |
| all? | With a block, returns true if all elements satisfy the condition. Always returns true for an empty array. |
| none? | Returns true if no element satisfies the condition. |
| count | Without arguments or a block, returns the number of elements. With a value or block, returns the count of matching elements. |
Sample Code
scores = [65, 82, 91, 78, 55]
# Use any? to check if at least one element satisfies the condition.
puts scores.any? { |s| s >= 90 } # true (91 exists)
puts scores.any? { |s| s >= 100 } # false
# Use all? to check if all elements satisfy the condition.
puts scores.all? { |s| s >= 50 } # true (everyone is 50 or above)
puts scores.all? { |s| s >= 80 } # false
# Use none? to check if no element satisfies the condition.
puts scores.none? { |s| s < 50 } # true (no one is below 50)
puts scores.none? { |s| s > 90 } # false (91 exists)
# Use count to count elements.
puts scores.count # 5 (total elements)
puts scores.count(82) # 1 (elements equal to 82)
puts scores.count { |s| s >= 80 } # 2 (elements 80 or above)
# Practical example: validation check.
email_list = ["a@example.com", "b@example.com", "invalid-email"]
all_valid = email_list.all? { |m| m.include?("@") }
puts all_valid # false
invalid_count = email_list.count { |m| !m.include?("@") }
puts "Invalid emails: #{invalid_count}" # Invalid emails: 1
Notes
These methods let you write concise condition checks across an entire array. They improve readability compared to using an each loop with a flag variable.
all? always returns true for an empty array (based on the mathematical concept that a universal statement over an empty set is vacuously true). If the behavior on empty arrays matters for your use case, check with empty? first.
To extract elements that match a condition, use select / reject. To simply check for the presence of a value, include? is also available.
If you find any errors or copyright issues, please contact us.