I don’t understand the following code:
ruby-1.9.1-p378 > puts "nil is false" unless nil
nil is false
=> nil
ruby-1.9.1-p378 > puts "nil isn't false" unless nil == false
nil isn't false
=> nil
In most languages (of a C-base, at least), if(!cond) and if(cond==false) evaluate the same. What’s going on here to make that not the case?
(I’d like the details of why, I understand that that is how it is.)
Ruby considers that
falseandnilare the only two “falsy” values, while everything else is “truthy”. This is by definition and can not be modified (at least in MRI). This definition is used for all builtin operators likeif,unless,while,until,cond ? if_truthy : if_falsey,||,&&, …Writing
foo == barwill always call the==method onfoowithbaras an argument. By default,nil,false,trueand all other immediates like symbols, etc…, are only equal to themselves. This could be changed, though:In Ruby 1.9, you can also redefine the operator
!, sounless foois not necessarily the same asif !fooor the contrary ofif foo:Not that anybody would recommend doing anything like this…