James Evans
James Evans

Reputation: 795

how to find out whether all array elements match some condition?

I have a big array and I need to know whether all its elements are divisible by 2.

I'm doing it this way, but it's sort of ugly:

_true = true
arr.each { |e| (e % 2).zero? || _true = false }
if _true == true
    # ...
end

How to do this without extra loops/assignments?

Upvotes: 8

Views: 3548

Answers (2)

Chowlett
Chowlett

Reputation: 46667

Ruby's got you covered.

if arr.all? {|e| (e % 2).zero?}

There's also any? if you need to check whether at least one element has a given property.

Upvotes: 18

sawa
sawa

Reputation: 168081

This will do.

arr.all?(&:even?)

Upvotes: 23

Related Questions