Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - test each array element, get one result

Tags:

arrays

ruby

fold

I want a one-liner to return true/false, that tests each element in an array for whether it's an Integer or not. So if any element in the array is not an Integer, it should return false, else true. Here's my try:

>> ([2,1,4].map {|x| (x.is_a? Integer)}).reduce {|x, result| x and result}
=> true
>> ([2,"a",4].map {|x| (x.is_a? Integer)}).reduce {|x, result| x and result}
=> false

Any other ideas to distill it down further?

like image 621
oaklodge Avatar asked Oct 05 '10 17:10

oaklodge


2 Answers

array.all?{ |x| x.is_a? Integer }
like image 109
Nakilon Avatar answered Sep 30 '22 07:09

Nakilon


ary.all?(&Integer.method(:===))
like image 39
Jörg W Mittag Avatar answered Sep 30 '22 07:09

Jörg W Mittag