Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 300
James Evans Avatar asked Oct 30 '12 14:10

James Evans


2 Answers

This will do.

arr.all?(&:even?)
like image 163
sawa Avatar answered Nov 15 '22 12:11

sawa


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.

like image 22
Chowlett Avatar answered Nov 15 '22 12:11

Chowlett