ハッシュや配列の中に特定の要素が存在するか確認する方法です。
emailが登録されていなかったら登録、されていたらメッセージ、みたいなイメージです。
任意のハッシュを判別
このようなハッシュを例にします。
nil
empty
に注目です。
@user = {
"id" => 1,
"name" => "Taro",
"age" => 26,
"from" => nil,
"sex" => "",
"created_at" => Sun, 21 Aug 2020 09:55:05,
"updated_at" => Sun, 21 Aug 2020 09:55:05
}
has_attribute?で判別
特定の要素自体があるかどうか判別します。
has_attribute?
でこのような結果が得られます。
@user.has_attribute?(:name) # => true
@user.has_attribute?(:from) # => true
@user.has_attribute?(:sex) # => true
@user.has_attribute?(:userid) # => false
少しややこしいのが、中身が nil
empty
だとしても結果はtrue
というところです。
要素自体があるかないかの判別ということです。
attribute_present?で判別
特定の要素の中身が存在するか判別します。
attribute_present?
でこのような結果が得られます。
@user.attribute_present?(:name) # => true
@user.attribute_present?(:from) # => false
@user.attribute_present?(:sex) # => false
@user.attribute_present?(:userid) # => エラー
要素は存在する前提で、中身が空かどうか判別します。
参考
ActiveRecordやハッシュ・配列などで使えるメソッドは他にもたくさんありますよー
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html