3

Lets say I have an array that looks like:

[true, true, false] 

And I am passing an operator along with the array which may be AND, OR or XOR.

So I want to calculate the logical value of array based on the operator specified.

ex:

for the given array [true, true, false] and the operator AND I should be able to perform in continuation for n number of elements in array

Steps: true AND true -> true, true AND false -> false

therefore the output should be false

the array can be an n number of boolean values.

1 Answer 1

3

The best and easiest way to do this is using reduce:

def logical_calculation(arr, op)
  op=='AND' ? arr.reduce(:&) : op=='OR' ? arr.reduce(:|) : arr.reduce(:^)
end

and also the other way is might be using inject

OPS = { "AND" => :&, "OR" => :|, "XOR" => :^ }

    def logical_calculation(array, op)
      array.inject(&OPS[op])
    end
Sign up to request clarification or add additional context in comments.

5 Comments

IIRC, inject and reduce is just an aliast to the same function. Try out yourself, both examples should be working exactly the same if you swap function names
The ternary method is absurd and should be removed. The version with the look-up table should be the only answer here.
inject/reduce is like map/select and length/size, they're just aliases.
You asked a question you were clearly already, or became relatively immediately, aware of the answer to and answered it yourself? Can you explain your reasoning? Additionally the first as @tadman stated is "absurd" and secondly assumes not "AND" or "OR" is "XOR" and the second will raise for any value not "AND", "OR" or "XOR". And in both cases these are not logical operations but rather bitwise (binary)operations. logical AND is && and logical OR is || (and and or are also technically logical but due to precedence are usually referred to as control flow operators).
Additionally this assumes array[0] is always a TrueClass or FalseClass otherwise errors abound

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.