简体   繁体   中英

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 .

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

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

SeeEnumerable#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? (aka 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? (aka has_value? )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM