I was doing a challenge on Code Wars where I was given an array "numbers" with several (sometimes repeating) integers and I had to return one unique integer. I passed the challenge but when I looked at all the previously submitted solutions, I noticed this reduce method:
def stray (numbers)
numbers.reduce(&:^)
end
I know what reduce method generally does but I haven't been able to find what the symbol ^ means. Could anyone please let me know its purpose?
The reduce method is used on arrays to combine all elements of that array into a single item.
The reduce method accepts a starting value and a block of code.
What you are using is a shorthand version of reduce which means the following:
numbers.reduce(&:^)
The & character will attempt to call the method on the argument itself when it is used as a last argument of a method call or definition. The ^ character signifies the bitwise XOR operator.
Inject is also an alias for reduce in Ruby.
You can read more here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With