Ruby - 测试每个数组元素,得到一个结果

时间:2010-10-05 17:00:23

标签: arrays ruby fold

我想要一个单行返回true / false,它测试数组中的每个元素是否为整数。因此,如果数组中的任何元素不是Integer,则应返回false,否则返回true。这是我的尝试:

>> ([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

还有其他想法可以进一步提炼它吗?

2 个答案:

答案 0 :(得分:19)

array.all?{ |x| x.is_a? Integer }

答案 1 :(得分:5)

ary.all?(&Integer.method(:===))