I just got through a troubling bug in my rails application and I discovered that the problem was that !0 was false. I was assuming that, that should be true.
I was under the impression that ! operator would reverse the bits in an integer so 0 would become all 1's and hence would be true.
That is not the case, why?
Also note from the rails console:
1.9.3p286 :002 > !0
=> false
1.9.3p286 :003 > 0
=> 0
1.9.3p286 :004 > !1
=> false
1.9.3p286 :005 > !!0
=> true
1.9.3p286 :006 > !0
=> false
1.9.3p286 :007 > !23
=> false
No it's not. :) Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.
false and nil are falsey , everything else is truthy .
In Ruby only false and nil are falsey. Everything else is truthy (yes, even 0 is truthy). In some languages, like C and Python, 0 counts as false. In fact, in Python, empty arrays, strings, and hashes all count as false.
The object true represents truth, while false represents the opposite. You can assign variables to true / false , pass them to methods, and generally use them as you would other objects (such as numbers, Strings, Arrays, Hashes).
Because 0
is not equivalent to false
. 0
is an integer value and the boolean value of all integers is true
. The only things that evaluate to false
are nil
and, explicitly, false
.
Given that 0
is true
, !0
is, intuitively, false
.
!
is not a bit-wise operator, it is a logical NOT
. Perhaps you meant ~0
?
In ruby there are only two values that evaluate to false in logical expressions: false and nil. Since 0 is neither of them, it evaluates to true and thus !true equals false.
From this blog
Most objects in Ruby will have a boolean value of true. Only two objects have a boolean value of false, these are the false object itself and the nil object.
So any integer (even 0) has a boolean value true
. And thus !0
evaluates to false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With