Understanding the #any? Method in Ruby
Ruby gives us a number of helper methods for checking certain conditions of arrays and enumerable objects.
The .any?
method is a helper method that returns true
if any element in the given enumerable evaluates to a true
value.
[""].any? # => true
[true].any? # => true
[{}].any? # => true
[[]].any? # => true
[0].any? # => true
{hello: "world"}.any? # => true
{}.any? # => false
[].any? # => false
[nil].any? # => false
[false].any? # => false
Note: ALL values in Ruby are evaluated to true
, except for false
and nil
. Even 0 evaluates to true
.
Passing a Block to Ruby's #any? Method
Beyond just checking if an array contains any truthy values, we can supply a custom block that checks a specific condition is true for any element in the array.
If any element in the array meets the condition specified in the block, the any?
method returns true.
[0, 1, 2, 3].any? { |n| n >= 3 } #=> true
[0, 1, 2, 3].any? { |n| n >= 4 } #=> false
Passing a Function to Ruby's #any? Method
If you have a method that you want to call on each element in a list, .any?
can help you determine if any element
[0, 1, 2, 3].any? { |n| isOdd?(n) } #=> true
[1, 3, 5, 7].any? { |n| isEven?(n) } #=> false
You can also call instance methods on each enumerated element and use any?
to quickly determine if your condition is met by anything in the given list.
[0, 1, 2, 3].any? { |n| n.present? } #=> true
[0, 1, 2, 3].any?(&:present?) # shorthand
Key Takeaways
The .any?
method returns true
if any element in the given object is truthy.
You can call .any?
on any type of enumerable object, including arrays and hashes.
A block can be passed as an argument to check if a specific condition is true for any value in the enumerable object.
Functions can be passed to scan through an enumerable object and check for more complex conditions.
And that's how the .any?
method works in Ruby!