Question

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
Was it helpful?

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.

OTHER TIPS

There's no such a thing as =! operator in Ruby. != is what checks for not equal.

So basically, when the parser is looking at the code and find an =, it looks for other operators that start with = such as ==. If it finds no match, which is the case here ( =! ), it considers the expression as an assignment, and assigns the right hand side to the left hand side. In this case, the right hand side of the = is ! 5, which is equal to false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top