boddhisattva boddhisattva - 4 months ago 9
Ruby Question

What is the difference between '&&' and '&' in Ruby

Recently, I observed a very interesting result in Ruby while making use of && and & for the input combination of 0 & 1.

Can someone please explain the below output with respect to the above mentioned two operators? The below is implemented using Ruby 2.0.0-p451

2.0.0-p451 :006 > 0 && 1
=> 1


2.0.0-p451 :008 > 0 & 1
=> 0


Thank you

Answer

&& is a boolean and. It returns the second argument if the first and the second argument is true. Since 0 and 1 are trueish in Ruby, 1 is returned.

& is a bitwise and. It compares the bit representation of the values. Since (imaging 8 bit) 00000000 (0) and 00000001 (1) have no 1 digits in common, 00000000 (0) is returned.

Comments