A concise explanation of nil v. empty v. blank in

2018-12-31 10:10发布

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here's the closest I've come:

  • blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

  • nil? objects are instances of NilClass.

  • empty? objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.

Is there anything missing, or a tighter comparison that can be made?

14条回答
像晚风撩人
2楼-- · 2018-12-31 10:14

exists? method can be used to check whether the data exists in the database or not. It returns boolean values either true or false.

查看更多
浪荡孟婆
3楼-- · 2018-12-31 10:17

A special case is when trying to assess if a boolean value is nil:

false.present? == false
false.blank? == true
false.nil? == false

In this case the recommendation would be to use .nil?

查看更多
爱死公子算了
4楼-- · 2018-12-31 10:18

Rails 4

an alternative to @corban-brook 's 'Array gotcha: blank?' for checking if an arrays only holds empty values and can be regarded as blank? true:

[ nil, '' ].all? &:blank? == true

one could also do:

[nil, '', "", " ",'  '].reject(&:blank?).blank? == true
查看更多
泛滥B
5楼-- · 2018-12-31 10:19

I made this useful table with all the cases:

enter image description here

blank?, present? are provided by Rails.

查看更多
谁念西风独自凉
6楼-- · 2018-12-31 10:20

One difference is that .nil? and .empty? are methods that are provided by the programming language Ruby, whereas .blank? is something added by the web development framework Rails.

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 10:21

Just a little note about the any? recommendation: He's right that it's generally equivalent to !empty?. However, any? will return true to a string of just whitespace (ala " ").

And of course, see the 1.9 comment above, too.

查看更多
登录 后发表回答