Zed
Zed

Reputation: 5931

Processing Array and returning boolean value

I'm wondering, what would be the easiest way to check if all the elements of Array conform to certain criteria and return boolean? Is there maybe a pattern in Ruby to call method on collection and then return boolean value? Standard Enumerable methods return either Array or nil, so I'm not sure where to look.I've wrote an example that works using grep, but I feel that if could be skipped with more idiomatic code:

 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

Upvotes: 2

Views: 645

Answers (2)

Antimony
Antimony

Reputation: 39451

Did you try Enumerable.all? {block} ? It seems like exactly what you're looking for.

Edit:

My Ruby is a bit rusty, but here's an example of how to use it

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

Upvotes: 4

Nir Alfasi
Nir Alfasi

Reputation: 53535

You can change:

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

with simply returning:

matched.length == array_collection.length

Like this:

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

Upvotes: 0

Related Questions