Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you perform boolean operations over all elements of an array and mix the result together?

Tags:

ruby

I want to AND or OR all the elements in an array, but with some control, as shown via the hash element selection. Here is the behavior that I wish to achieve:

a = [{:a => true}­, {:a => false­}]
a.and_map{ |hash_element| hash_element[:a] }
#=> false
a.or_map{ |hash_element| hash_element[:a] }
#=> true

Is there a slick, clean way to do this in Ruby?

like image 356
NullVoxPopuli Avatar asked Mar 20 '12 16:03

NullVoxPopuli


People also ask

How do you use Boolean operators?

Boolean Operators are simple words (AND, OR, NOT or AND NOT) used as conjunctions to combine or exclude keywords in a search, resulting in more focused and productive results. This should save time and effort by eliminating inappropriate hits that must be scanned before discarding.

What are the three different types of Boolean operators?

Boolean operators form the basis of mathematical sets and database logic. They connect your search words together to either narrow or broaden your set of results. The three basic boolean operators are: AND, OR, and NOT.


1 Answers

You can use all? and any? for that:

a = [{:a => true}, {:a => false }]
a.any? { |hash_element| hash_element[:a] }
#=> true
a.all? { |hash_element| hash_element[:a] }
#=> false
like image 61
Michael Kohl Avatar answered Oct 07 '22 04:10

Michael Kohl