I don't understand the following code:
ruby-1.9.1-p378 > puts "nil is false" unless nil
nil is false
ruby-1.9.1-p378 > puts "nil isn't false" unless nil == false
nil isn't false
Ruby considers that
nil are 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 like
cond ? if_truthy : if_falsey,
foo == bar will always call the
== method on
bar as an argument. By default,
true and all other immediates like symbols, etc..., are only equal to themselves. This could be changed, though:
def nil.==(bar) super || bar == false end puts "nil == false" if nil == false # => "nil == false"
In Ruby 1.9, you can also redefine the operator
unless foo is not necessarily the same as
if !foo or the contrary of
def true.! true end puts "True?" if true # => "True?" puts "or not?" if !true # => "or not?"
Not that anybody would recommend doing anything like this...