Ruby 处理数组并返回布尔值

Ruby 处理数组并返回布尔值,ruby,Ruby,我想知道,检查数组的所有元素是否符合某些条件并返回布尔值的最简单方法是什么?Ruby中是否有一种模式可以调用集合上的方法,然后返回布尔值?标准可枚举方法返回Array或nil,因此我不确定该在何处查找。我已经编写了一个使用grep的示例,但我觉得可以使用更惯用的代码跳过if: def all_matched_by_regex?(regex) array_collection = ['test', 'test12', '12test'] matched = array_co

我想知道,检查数组的所有元素是否符合某些条件并返回布尔值的最简单方法是什么?Ruby中是否有一种模式可以调用集合上的方法,然后返回布尔值?标准可枚举方法返回Array或nil,因此我不确定该在何处查找。我已经编写了一个使用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
你试过了吗?这似乎正是你要找的

编辑:

我的红宝石有点生锈,但这里有一个如何使用它的例子

  regex = /test/
=> /test/
   array_collection = ['test', 'test12', '12test']
=> ["test", "test12", "12test"]
   array_collection.all? {|obj| regex =~ obj}
=> true
你试过了吗?这似乎正是你要找的

编辑:

我的红宝石有点生锈,但这里有一个如何使用它的例子

  regex = /test/
=> /test/
   array_collection = ['test', 'test12', '12test']
=> ["test", "test12", "12test"]
   array_collection.all? {|obj| regex =~ obj}
=> true
您可以更改:

 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
您可以更改:

 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

是的,就是这样;然而,人们应该意识到,所有这些?空集合的行为在这种情况下返回true。我建议你检查一下?还有,只是反转模式来检查。就是这样,是的!我真的不知道我是怎么跳过的。谢谢。是的,就是这样;然而,人们应该意识到,所有这些?空集合的行为在这种情况下返回true。我建议你检查一下?还有,只是反转模式来检查。就是这样,是的!我真的不知道我是如何跳过任何/全部的。谢谢。我很确定这只算作链接回答+评论。请注意,这里不欢迎只提供链接的答案。@Jan有一个标准库函数,它完全按照要求执行。还有什么要说的吗?一个代码示例就好了。一个针对OP情况的代码示例——甚至更好。我很确定这只算作一个链接回答+一条评论。请注意,这里不欢迎只提供链接的答案。@Jan有一个标准库函数,它完全按照要求执行。还有什么要说的吗?一个代码示例就好了。一个针对OP情况的代码示例——甚至更好。