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