Yshmarov
Yshmarov

Reputation: 3729

Array of hashes: Validate presence of Key-Value pair?

running the command

Company.first.employees.pluck(:roles)

produces the result

[{"admin"=>false, "editor"=>false, "viewer"=>false}, {"admin"=>true}] 

As you see, it is an array of hashes.

How can I check if any of the key-value pairs contains "admin"=>true?

I would imagine it working somewhat like this (does not work)

Company.first.employees.pluck(:roles).values.include?("admin"=>true)

The desired result produces true/false if there are any key-values with "admin"=>true.

Upvotes: 0

Views: 297

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

arr = [
  { "admin"=>false, "editor"=>false, "viewer"=>false },
  { "admin"=>true, "editor"=>false }
]

Does any element of arr contain the key-value pair ["admin", true]?

arr.any? { |h| h["admin"] == true }
  #=> true

See Enumerable#any?.

Return an array of the elements of arr that contain the key-value pair ["editor", false]

arr.select { |h| h["admin"] == true }
  #=> [{"admin"=>true, "editor"=>false}]

See Array#select.

Count the number of elements of arr that contain the key-value pair ["editor", false]

arr.count { |h| h["editor"] == false }
  #=> 2

See Array#count.

Count the number of elements of arr that contain the key-value pairs ["editor", false] and ["viewer", false]

arr.count { |h| h["editor"] == false && h["viewer"] == false }
  #=> 1

Return an array of the elements of arr that contain the key "admin"

arr.select { |h| h.key?("admin") }
  #=> [{"admin"=>false, "editor"=>false, "viewer"=>false},
  #    {"admin"=>true, "editor"=>false}]

See Hash#key? (a.k.a. has_key?)

Return an array of the element of arr that contain the value true

arr.select { |h| h.value?(true) }
  #=> [{"admin"=>true, "editor"=>false}]

See Hash#value? (a.k.a. has_value?)

Upvotes: 1

Anuj Biyani
Anuj Biyani

Reputation: 329

This should do it:

Company.first.employees.pluck(:roles).any? { |roles| roles["admin"] }

Basically: for every element in Company.first.employees.pluck(:roles), check if any of them return true for roles["admin"]. If they do, the whole any? check returns true.

https://ruby-doc.org/core-2.7.1/Enumerable.html#method-i-any-3F

Upvotes: 2

Related Questions