3

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'?

2
  • 5
    Change the last line to test.any? or drop that line and change test.map!... to: test.map { |a,b| a == Rational(a,b).numerator }.any? (no need for !). test.any? returns true if any element of test is "thruthy" (neither nil nor false); else returns false. Commented Nov 8, 2014 at 18:14
  • args.combination(2).any? { |a,b| a == Rational(a,b).numerator } Commented Nov 8, 2014 at 23:47

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Replace :& with :| (Boolean AND with Boolean OR).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.