.nil? , .empty? .blank? .present?区别:
.nil? 判断对象是否存在(nil)。不存在的对象都是nil的。
nil.nil? =>true
false.nil? =>false
1.nil? =>false
0.nil? =>false
"".nil? =>false
[ ].nil? =>false
{ }.nil? =>false
.empty? 前提是对象已存在,判断是否为空字段,比如空字符串,空数组,空对象。
"".empty? =>true
" ".empty? =>false 注意有空格
"abc".empty? =>false
[ ].empty? =>true
[ nil ].empty? =>false
[1,2,3].empty? =>false
1.empty? => NoMethodError: undefined method `empty?'
{}.empty? =>true
.blank?等于同时满足 .nil? 和 .empty? 。如果对象是false, empty, 空白字符. 例:
"", " ", nil , [], 和{}都算是blank。
object.blank? 相当于object.nil? || object.empty?
.nil? 和 .empty? 是ruby的方法。 .blank?和present? 是rails的方法,需要在rails环境下才能测试,rails c。
true.blank? =>false
false.blank? =>true
"true".blank? =>false
"".blank? =>true
" ".blank? =>true
"\n".blank? =>false
'\n'.blank? =>false
{}.blank? =>true
1.blank? =>false
[].blank? =>true
nil.blank? => true
present?方法是blank?相反的方法,用于判断是否存在,present?与!blank?相同,或(!present?与blank?)
nil.present? =>false
[].present? =>false
"hello".present? =>true
["a"].present? =>true
网友评论