1
3

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 5 years have passed since last update.

rails: present? blank? nil? unless

Last updated at Posted at 2016-11-07

それぞれの定義

present?の意味

対象のオブジェクトがnilもしくは空の場合にfalseそれ以外の場合はtrueを返す。

こちらより

An object is present if it's not blank.

以下コメントより引用

test.rb
require "active_support/core_ext/object"

puts "".present?     #=> false
puts "   ".present?  #=> false
puts [].present?     #=> false
puts({}.present?)    #=> false 
puts false.present?  #=> false

nil?の意味

対象のオブジェクトがnilであればtrueを返す。

blank?

こちらより

An object is blank if it's false, empty, or a whitespace string. For example, false, '', ' ', nil, [], and {} are all blank.

falseを始めとした空欄もすべてtrueと返してくれる。
言い換えればpresent?の真逆。つまり!blank?present?は同義。よって" ".blank? #trueになる。

例えば

      desc "migrate category names to new db"
    task migrate_category_names: :environment do
      Category.find_each do |category|
        path = category.path.gsub("-", "/").gsub("_", "-")
        matched_record = GakkiManiaCategoryPathSetting.find_by(path: path)
        if matched_record.present?
          if matched_record.name.present?
          category.update(name: matched_record.name)
          end
        end
      end      
    end

これはmatched_recordnilかそうでないかの精査を行っているが、仮にその行をunless matched_record.nil?としても同じである。回りくどいのでやらないほうが良いと思うが。このようにifを使わなくてもunless AでAがfalseのときに以下の処理を実行みたいなことも可能。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?