PJCHENder 未整理筆記

[Rails] 判斷內容是空或有

2017-10-13

[Rails] 判斷內容是空或有

@(Ruby on Rails)[rails, railsTips]

tags: ruby, rails, empty, blank, present, nil

Rails 方法

.blank?

  • Rails Method
  • 任何型態都可使用不會噴錯
  • 空白的字串也算空
1
2
3
4
5
6
7
nil.blank?     #true
[].blank? #true
{}.blank? #true
"".blank? #true
" ".blank? #true
"abc".blank? #false
123.blank? #false

.present?

  • Rails Method
  • 任何型態都可使用不會噴錯
  • 空白的字串也算空
1
2
3
4
5
6
7
nil.present?   #false
[].present? #false
{}.present? #false
"".present? #false
" ".present? #false
"abc".present? #true
123.present? #true

.persisted? & new_record

判斷 Object 是否已經存在資料庫的 method:

  • new_record: 尚未存入資料庫
  • persisted: 已存入資料庫
1
2
3
4
5
6
7
a = User.new   #還沒存入資料庫以前
a.persisted? #false
a.new_record? #true

a.save #存入資料庫
a.persisted? #true
a.new_record? #false

Ruby 內建方法

.empty?

  • Ruby Method
  • 可以判斷 [], {} 和字串
  • 無法判斷 nil 和數值(會噴錯)
  • 字串內有空白就不算 empty
1
2
3
4
5
6
7
nil.empty?     #NoMethodError: undefined method `empty?' for nil:NilClass
[].empty? #true
{}.empty? #true
"".empty? #true
" ".empty? #false
"abc".empty? #false
123.empty? #NoMethodError: undefined method `empty?' for 123:Fixnum

.any?

  • Ruby Method
  • 只能判斷 []{}
1
2
3
4
5
6
7
nil.any?       #NoMethodError: undefined method `any?' for nil:NilClass
[].any? #false
{}.any? #false
"".any? #NoMethodError: undefined method `any?' for "":String
" ".any? #NoMethodError: undefined method `any?' for "":String
"abc".any? #NoMethodError: undefined method `any?' for "":String
123.any? #NoMethodError: undefined method `any?' for 123:Fixnum

.nil?

  • Ruby Method
  • 只能判斷該物件是否為 nil
1
2
3
4
5
6
7
nil.nil?       #true
[].nil? #false
{}.nil? #false
"".nil? #false
" ".nil? #false
"abc".nil? #false
123.nil? #false

.exist?

1
User.where(name: 'Aaron').exist?		# []

參考

掃描二維條碼,分享此文章