the difference between nil, true, false, blank and empty

The Nil Expression

It’s pretty important that you understand the difference of these expressions. To begin, let’s start with nil. Nil is the ruby way of saying NULL. Whenever there is an expression that returns nothing, we get a nil that specifies that. For instance, in a find_by, if the record is not there we get nil as a result. Notice that find returns RecordNotFound exception. As everything is an object in Ruby, Nil is also an object (of class NilClass). Nil is not the same as false.

False/True Expressions

In Ruby (and Rails of course), every expression that is not nil or false is considered true. False and True expressions work pretty much as expected, but pay attention to the fact that, again, they are objects (TrueClass, FalseClass). Take a look at the console below :

irb(main):053:0> 0==1
=> false
irb(main):054:0> 1==1
=> true
irb(main):055:0> nil==true
=> false
irb(main):056:0> nil==false
=> false
irb(main):057:0> 0==true
=> false
irb(main):058:0> 0==false
=> false
irb(main):060:0> true.class
=> TrueClass

 Nil is not either true or false. 0 is not either true or false(or nil). It’s just 0.

The Blank? Expression

Blank is a Rails expression that checks whether an object is either nil or false. Notice that blank evaluates correctly if the object is a space padded string.

irb(main):066:0> ''.blank?
=> true
irb(main):067:0> nil.blank?
=> true
irb(main):068:0> '     '.blank?
=> true
irb(main):069:0> 'a'.blank?
=> false
irb(main):070:0> false.blank?
=> true
irb(main):071:0> true.blank?
=> false
irb(main):073:0> [].blank?
=> true
irb(main):074:0> ['a'].blank?
=> false

 

 The Empty? Expression

 

Empty can only be used in some objects like an array or a string. As you can guess, it checks whether an object is empty (empty string, no elements array etc).

irb(main):078:0> '     '.empty?
=> false
irb(main):079:0> ''.empty?
=> true
irb(main):080:0> [].empty?
=> true
irb(main):081:0> ['a'].empty?
=> false
irb(main):082:0> nil.empty?
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
 from (irb):82
 from :0

A space padded string is not empty, although it’s blank. Also notice that nil.empty? is an incorrect expression, because the nil object does not have an empty method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值