Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `x =! 5` return false?

I've been studying operator precedence and it was explained to me that x =! 5 returns false. I can't seem to explain why to myself again. I know =! isn't a operator so then x and 5 remain. So does that mean Ruby doesn't know what to do? If so ruby should return an error because x can have no value? Does Ruby stop at the operator and then assign a value of false to x?

x =! 5 
=> false
like image 354
HandDisco Avatar asked Jan 15 '14 12:01

HandDisco


People also ask

Which operator returns true or False?

The true operator returns the bool value true to indicate that its operand is definitely true. The false operator returns the bool value true to indicate that its operand is definitely false.

Which operator returns False when two things are equal?

The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is the return value for x == Y True or False?

x == y compares x and y . The result of x == y will be true if x and y are equal, false otherwise.

What does X === Y means?

Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal. x != y.


1 Answers

This is because x =! 5 is being interpreted as x = (!5) (! has higer precedence than =). In Ruby every object is true except nil and false. 5 has truthy value which you are negating using the operator !. So false as result is being assigned to the local variable x.

! Called Logical NOT Operator - is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make false.

like image 96
Arup Rakshit Avatar answered Oct 13 '22 07:10

Arup Rakshit