ruby nil? empty? blank? 的区别

ruby nil? empty? blank?

一句话区别: nil?与empty? 除了对象用nil?其他用empty?判断 ,blank?的用法几乎是前两者的结合体

nil?用于对象 object

sky = nil
sky.nil?  # => true
其他的对象的都为 object.nil? 都为false 如数据库的一个属性为空,则 属性.nil? # => true

empty? 用于string 和 array 还有hash

# Array
[].empty?   #=> true
# String
"".empty?   #=> true
但是 “ ” .empty? #=> false

 blank?  对象类

 "", nil, [], and {}.blank? #=> true

This simplifies

if !address.nil? && !address.empty?

to

if !address.blank?

看似blank? 是 nil? 和 empty?的结合体,但实际上还是有区别的 如: " ".empty? #=> false, " ".blank #=> true

.nil?

原文地址:https://www.cnblogs.com/chenzhenzhen/p/3858058.html