hellothere1 - 7 months ago 53

Ruby Question

I have been learning ruby for the last few weeks and I came across something like:

`array = [10, 20, 20];`

array.reduce(:^)

# => 10

which evaluated to 10.

The purpose of the code was to find an element with an odd number of occurrences within a sequence such as

`[10, 20, 20]`

Does anyone have a relatively simple explanation of how this works?

Answer

`reduce`

combines all the elements of an `Enumerable`

by applying a binary operation. `^`

is the bitwise exclusive OR (XOR) operator.

`array.reduce(:^)`

performs the bitwise XOR of the elements of `array`

. For `array = [10, 20, 20]`

, this performs `(10 ^ 20) ^ 20`

, giving the result `10`

.

The bitwise XOR of a number and itself is 0 and XOR is associative (the order is not important). Every pair of identical numbers in the array is therefore cancelled out, leaving the XOR of any numbers that occur an odd number of times. If there is a single number in the array that occurs an odd number of times, then this number will be the result.

Source (Stackoverflow)