LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】ハッシュや配列に特定要素が存在するか判別 [ActiveRecord] [has_attribute?]

Posted at

ハッシュや配列の中に特定の要素が存在するか確認する方法です。
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

0
0
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
0
0