Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!0 is false in rails. Why? [closed]

Tags:

ruby

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 
like image 971
Karan Verma Avatar asked May 11 '13 09:05

Karan Verma


People also ask

Does 0 evaluate to false in Ruby?

No it's not. :) Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

Is nil false in rails?

false and nil are falsey , everything else is truthy .

Is zero truthy Ruby?

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.

What does false mean in rails?

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


3 Answers

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?

like image 144
Ant P Avatar answered Sep 18 '22 14:09

Ant P


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.

like image 26
Erez Rabih Avatar answered Sep 21 '22 14:09

Erez Rabih


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

like image 30
RedBaron Avatar answered Sep 19 '22 14:09

RedBaron