LoginSignup
3
1

More than 3 years have passed since last update.

nil? empty? blank? present? の違い

Last updated at Posted at 2020-10-20

この記事ではmacOS Catalina10.15.6にインストールしたRuby 2.6.5を使っています。
nil? empty? blank?の区別をはっきりさせたかったので書きました。

nil?

  • 「何も存在しない」状態です。器も中身も何もありません。
  • だからnilという言葉でしか表せないのですね。
name = nil 
name.nil? #=> true
  • 例えば、以下の例は全てnilにはならないので注意ですね。
array = [] #=> false
zero = 0 #=> false
name = ""  #=>false
hash = {} #=> false

empty?

  • 「器はあるけど中身がない」状態です。これはイメージしやすいですね。 空のお皿という状況でしょうか。
  • ただし、nilにempty?メソッドを使うとエラーが出てしまうので、よく見極めてから使いましょう。
array = [] 
array.empty? #=> true

animal = ""
animal.empty? #=> true

name = nil
name.empty? #=> false

blank?

  • nil?とempty?を合体させたようなメソッドです。
  • nilとemptyのどちらでもtrueを返すのですね。
array =[]
array.blank? #=> true

name = nil
name.nil? #=> true

present?

  • 「器があって、中身がある」状態です。 つまり、中身があればOKということですね。
age = 24
age.present? #=> true

3
1
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
3
1