LoginSignup
1365
1242

More than 5 years have passed since last update.

nil? empty? blank? present? の使い分け

Posted at

まず、nil?とempty?はrubyのメソッドで、blank?とpresent?はrailsで拡張されたメソッド(つまりrubyでは使えない)ってことを覚えておく。

-

nilは存在しないという意味。

対して ""は「何も無い」が存在している。空白の存在。

book.nil?

もしbook自体が存在しないなら、上記はtrueを返す。

empty?は「入れ物」は存在するのが前提。

book.empty?
description.empty?

は、bookやdescriptionそのものは存在していることが前提で、その配列の中身が空か、文字列の中身が空の場合にtrueを返す。
配列や文字列そのもの(入れ物)が無い場合にはNoMethodErrorが発生する。空ですか?と聞いてるわけだから、少なくとも「入れ物」が存在しないとダメってことか。

blank?は、nil?とempty?の合わせ技

では、中身が空か、または入れものそのものが存在しないときの判定はどうなるか。blank?が使える。empty?とnil?を足したようなものだ。
nilと空のオブジェクトを判定できる。

unless description.blank?
end

と書けば、descriptionの文字列が空か、そもそもdescription自体が存在しない場合に処理をスキップできる。

present?は、!blank?と同じ意味

ちなみに上の処理は present?を使って

if description.present?
end

と書ける。

-

nil? すべてのオブジェクトに定義されている。nilのときのみtrueを返す。
empty? 文字列の長さが0のとき、または配列が空のときにTrueを返す。もちろん数値には定義されていない。
blank? railsの拡張。nil, "", " ", [], {} のいずれかでTrueを返す。

1365
1242
2

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
1365
1242