在學習Ruby on Rails的過程中,總是會發現了很多功能相似方法
這次就來了看看nil?、empty? blank? present?之間的差異吧!
nil?是Ruby裡的方法,可以使用在任何物件身上,用來判斷該物件是否為nil
> nil.nil? => true
> [].nil? => false
> "Ruby"].nil? => false
> {}.nil? => false
> {name: "Ruby"}.nil? => false
> "".nil? => false
> " ".nil? => false
> "String".nil? => false
> 1010.nil? => false
再來試試看,指定一個變數a為nil
a = nil
a.nil? => true
此時的a為nil,所以a.nil?也為回傳true了
所以我們得到一個結果,只要該物件是nil就會回傳true。
empty?也是Ruby的方法,這個方法可以使用在string,array或hash身上,用來檢查集合Collection是否為空,所以當string,array或hash的length為0則會回傳true,如果不是就會回傳false。
> nil.empty? => NoMethodError
> [].empty? => true
> ["Ruby"].empty? => false
> {}.empty? => true
> {name: "Ruby"}.empty? => false
> "".empty? => true
> " ".empty? => false
> "String".empty? => false
1010.empty? => NoMethodError
blank?是Rails的方法,來自Active Record,跟.empty?一樣可以使用在string、array、hash的方法,也可以使用在nil。但是當String的物件不管是否為空白.blank?都會回傳true,以及在NilClass時也是回傳true。
nil.blank? => true
[].blank? => true
["Ruby"].blank? => false
{}.blank? => true
{name: "Ruby"}.blank? => false
"".blank? => true
" ".blank? => true
"String".blank? => false
1010.blank? => false
.present?也是Rails方法,來自Active Record,present?這個方法與.blank?的用法恰好相反。
最簡單說就是!obj.blank? == obj.present?
nil.present? => false
[].present? => false
["Ruby"].present? => true
{}.present? => false
{name: "Ruby"}.present? => true
"".present? => false
" ".present? => false
"String".present? => true
1010.present? => true
最後整理成表格,大概就是樣了
nil? | empty? | blank? | present? | |
---|---|---|---|---|
Ruby | Ruby | Rails | Rails | |
nil | true | NoMethodError | true | false |
[] | false | true | true | false |
{} | false | true | true | false |
"" | false | true | true | false |
" " | false | false | true | false |
"String" | false | false | false | true |
1010 | false | NoMethodError | false | true |
參考連結:
How to use .nil? .empty? .blank? .present? in Rails 5
.nil? .empty? .blank? .present? 傻傻分不清楚?