Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of caret symbol( ^ ) in Ruby

Tags:

1 ^ 1 # => 0  1 ^ 2 # => 3  5 ^ 6 # => 3 

These are the results I am getting. Can, please, somebody explain how ^ works?

like image 781
shajin Avatar asked Aug 23 '11 14:08

shajin


People also ask

What does :+ mean in Ruby?

inject(:+) is not Symbol#to_proc, :+ has no special meaning in the ruby language - it's just a symbol.

What is the caret used for in JavaScript?

A caret (sometimes called a "text cursor") is an indicator displayed on the screen to indicate where text input will be inserted.

What is :& in Ruby?

The and keyword in Ruby takes two expressions and returns “true” if both are true, and “false” if one or more of them is false. This keyword is an equivalent of && logical operator in Ruby, but with lower precedence.

What is the use of caret in Python?

It's a bitwise XOR (exclusive OR). It evaluates to True if and only if its arguments differ (one is True , the other is False ). A slightly more illustrative example might include both numbers having 1 in the same bit to make it clear that 1 xor 1 = 0 .


1 Answers

It's a bitwise XOR operator.

For each bit in the binary representation of the operands, a bitwise XOR will get a 1 bit if one of the corresponding bits in the operands is 1, but not both, otherwise the XOR will get a 0 bit. Here's an example:

5     = 101 6     = 110 5 ^ 6 = 011 = 3 
like image 177
Rafe Kettler Avatar answered Sep 20 '22 05:09

Rafe Kettler