[Ruby] [Rails] Determine if a particular element exists in a hash or array [ActiveRecord] [has_attribute?]

1 minute read

It is a method to check whether a particular element exists in a hash or array. It is an image like if the email is not registered, it is registered, if it is registered it is a message.

Determine any hash

Let’s take such a hash as an example. Notice the 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
}

Determined by ##has_attribute?

Determines if a particular element itself is present. You can get this result with has_attribute?.

@user.has_attribute?(:name) # => true
@user.has_attribute?(:from) # => true
@user.has_attribute?(:sex) # => true
@user.has_attribute?(:userid) # => false

The tricky part is that the result is true even if the content is nil empty. It is the determination of whether or not the element itself exists.

Determined by ##attribute_present?

Determines if the content of a particular element is present. You can get a result like this with attribute_present?.

@user.attribute_present?(:name) # => true
@user.attribute_present?(:from) # => false
@user.attribute_present?(:sex) # => false
@user.attribute_present?(:userid) # => error

Determines whether the element is empty, assuming the element exists.

reference

There are many other methods that can be used with ActiveRecord, hashes, arrays, etc. https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html

Tags: ,

Updated: