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

问题描述 投票:11回答:2

我想要一个单行返回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

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

arrays ruby fold
2个回答
19
投票
array.all?{ |x| x.is_a? Integer }

5
投票
ary.all?(&Integer.method(:===))
© www.soinside.com 2019 - 2024. All rights reserved.