Search code examples
rubybooleanoperator-precedence

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

Solution

  • 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.