处理数组并返回布尔值

时间:2013-08-11 20:27:42

标签: ruby

我想知道,检查Array的所有元素是否符合某些条件并返回布尔值的最简单方法是什么? Ruby中是否有一种模式可以在集合上调用方法然后返回布尔值?标准Enumerable方法会返回Arraynil,所以我不确定在哪里查看。我已经编写了一个使用grep的示例,但我觉得可以使用更多惯用代码跳过if

 def all_matched_by_regex?(regex)

     array_collection = ['test', 'test12', '12test']
     matched = array_collection.grep(regex)
     if matched.length == array_collection.length
        return true
     end
     return false
    end

2 个答案:

答案 0 :(得分:4)

你试过Enumerable.all? {block} 吗?这看起来就像你正在寻找的。

编辑:

我的Ruby有点生疏,但这是一个如何使用它的例子

  regex = /test/
=> /test/
   array_collection = ['test', 'test12', '12test']
=> ["test", "test12", "12test"]
   array_collection.all? {|obj| regex =~ obj}
=> true

答案 1 :(得分:0)

您可以更改:

 if matched.length == array_collection.length
        return true
     end
     return false

只需返回:

matched.length == array_collection.length

像这样:

def all_matched_by_regex?(regex)    
   array_collection = ['test', 'test12', '12test']
   matched = array_collection.grep(regex)
   matched.length == array_collection.length
end
相关问题