Search code examples
rubyboolean-operations

Method over Boolean array should return true if any value in the array is true


This code works very well:

def is_rel_prime?(*args)                              #1
  test = args.combination(2).to_a                     #2
  test.map! { |a,b| a == Rational(a,b).numerator }    #3
  test.reduce (:&)                                    #4
end

> is_rel_prime?(3,4,5) #=> true
> is_rel_prime?(7,12,14) #=> false
> is_rel_prime?(7,12,15) #=> false

What do I replace the (:&) with so that it will return 'true' if ANY ONE (or more) of the array elements is 'true'?


Solution

  • Your code there is testing bool & bool & bool. Boolean#& is equivalent to && in general usage. As you might suspect, the corollary here is Boolean#|, which is equivalent to || in general usage. So, in your code, you would use test.reduce(:|) to decide if any boolean in the list is true.

    That said, Cary is correct in that Ruby already has facilities for checking the truthiness of any value in an enumerable, via Enumerable#any? (and can check the truthiness of all values via Enumerable#all?), so you should just use those rather than rolling your own checker.