if(!x) vs if(x==false) in ruby

前端 未结 3 1397
借酒劲吻你
借酒劲吻你 2020-12-16 15:15

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         


        
3条回答
  •  不思量自难忘°
    2020-12-16 16:09

    nil is not equal to false by comparison over == because their semantic content is different (nil is no information, false is a boolean value). However, if you try to evaluate nil in a boolean context, it will be considered False, mostly for convenience' sake and idiomatic compatibility with other languages.

    nil == a <=> nil != a <=> false is going to be the case for virtually any value of a except for nil.

    So you can only tell that 'nil is not true' and 'nil is nil'. This is as far as ruby goes in its ways.

提交回复
热议问题