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

I want AND or OR all the elements of the array, but with some control, as shown by selecting hash elements. Here is the behavior I want 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 smooth, clean way to do this in Ruby?

+6
source share
2 answers

Can you use all? and any? for this:

 a = [{:a => true}, {:a => false }] a.any? { |hash_element| hash_element[:a] } #=> true a.all? { |hash_element| hash_element[:a] } #=> false 
+17
source
 a = [{:a => true}, {:a => false}] a.all?{ |elem| elem[:a] } a.any?{ |elem| elem[:a] } 
+3
source

Source: https://habr.com/ru/post/911220/


All Articles