0
0
RubyHow-ToBeginner · 3 min read

How to Use all Method in Ruby: Syntax and Examples

In Ruby, the all? method checks if every element in a collection meets a given condition and returns true or false. You use it by calling all? with a block that defines the condition to test each element.
📐

Syntax

The all? method is called on an enumerable collection like an array or hash. It takes a block with a condition that each element is tested against. If all elements satisfy the condition, it returns true; otherwise, it returns false.

Basic syntax:

collection.all? { |element| condition }
ruby
collection.all? { |element| condition }
💻

Example

This example checks if all numbers in an array are positive using all?. It returns true only if every number is greater than zero.

ruby
numbers = [1, 2, 3, 4, 5]
result = numbers.all? { |num| num > 0 }
puts result

numbers2 = [1, -2, 3]
result2 = numbers2.all? { |num| num > 0 }
puts result2
Output
true false
⚠️

Common Pitfalls

One common mistake is forgetting to provide a block, which makes all? check if all elements are truthy instead of a custom condition. Another is using all? on an empty collection, which always returns true because there are no elements to disprove the condition.

ruby
arr = [nil, true, 99]
puts arr.all? # returns false because nil is falsey

arr2 = []
puts arr2.all? { |x| x > 0 } # returns true because array is empty
Output
false true
📊

Quick Reference

  • Returns true if all elements satisfy the block condition.
  • Returns false if any element fails the condition.
  • Returns true for empty collections.
  • Without a block, checks if all elements are truthy.

Key Takeaways

Use all? with a block to test if every element meets a condition.
all? returns true for empty collections by default.
Without a block, all? checks if all elements are truthy.
Remember that all? stops checking as soon as it finds a false element.
Common mistake: forgetting the block changes the behavior of all?.