hellothere1 hellothere1 - 4 months ago 35
Ruby Question

How does using Array#reduce in this way work?

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

array = [10, 20, 20];


# => 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?


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.