0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

nil?、empty?の使い分け

Posted at

一応自分用です。備忘録として残します。なので結論は出てません。

nil?

変数.nil?

Rubyの標準メソッド。nilの場合のみtrueを返し、それ以外はfalse

下の時に使うのかな。

irb(main):001:0> a = Model.find_by(id: 100)
  TRANSACTION (0.2ms)  BEGIN
  Plant Load (0.7ms)  SELECT `models`.* FROM `models` WHERE `models`.`id` = 100 LIMIT 1
=> nil  

empty?

変数.empty?

Rubyの標準メソッド。空の文字列や空の配列の場合にtrueを返す。nilに対して呼び出すとNoMethodErrorが発生

したの時に使うのかな。

irb(main):007:0> a = Model.where("column LIKE ?", "#{Date.today.year}-#{Date.today.month}%").where(user_id: 100)
  Plant Load (0.6ms)  SELECT `mode.s`.* FROM `models` WHERE (column LIKE '2022-11%') AND `plants`.`user_id` = 100
=> []  
.
.
.
irb(main):008:0> a.class
=> Model::ActiveRecord_Relation

出典

感想

簡単な気づきを書いています。
間違っているかもしれません。
しかし違いがあることに気がつけてよかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?