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=> falseirb(main):054:0> 1==1=> trueirb(main):055:0> nil==true=> falseirb(main):056:0> nil==false=> falseirb(main):057:0> 0==true=> falseirb(main):058:0> 0==false=> falseirb(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?=> trueirb(main):067:0> nil.blank?=> trueirb(main):068:0> '     '.blank?=> trueirb(main):069:0> 'a'.blank?=> falseirb(main):070:0> false.blank?=> trueirb(main):071:0> true.blank?=> falseirb(main):073:0> [].blank?=> trueirb(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?=> falseirb(main):079:0> ''.empty?=> trueirb(main):080:0> [].empty?=> trueirb(main):081:0> ['a'].empty?=> falseirb(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.

而消极的人则在每个机会都看到某种忧患。

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

相关文章:

你感兴趣的文章:

标签云: