Ashish Jambhulkar
Ashish Jambhulkar

Reputation: 1504

Final logical value of boolean array in ruby

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.

Upvotes: 3

Views: 1279

Answers (1)

Ashish Jambhulkar
Ashish Jambhulkar

Reputation: 1504

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

Upvotes: 3

Related Questions