Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does :^ in reduce method mean?

Tags:

ruby

reduce

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?

like image 819
ollsop Avatar asked Jul 30 '26 10:07

ollsop


1 Answers

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.

like image 190
tomerpacific Avatar answered Aug 02 '26 10:08

tomerpacific



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!