简体   繁体   中英

Iterate through an array or hashes to find a key in Ruby

I keep find only answers that iterate through an array of hashes to find a particular value. I want to iterate through an array of hashes to find a key. I am trying to access the key :labels. The array changes length and position of elements each time, so i cannot rely on a hardcoded index. Here is my array:

array = [
 {:status=>"100", 
  :status_msg=>"OUT_OF_ZONE", :order_ref=>"S", :order_id=>"28704622",
  :price=>"0", :"@xsi:type"=>"tns:Result"},
 {:status=>"100", 
  :status_msg=>"OUT_OF_ZONE", :order_ref=>"4", :order_id=>"28704623",
  :price=>"0", 
  :labels=>{:label_str=>"**%*%"}}
]

In Ruby 2.3+ you can use Hash#dig which returns the value of a nested key or nil.

labels = array.map{ |h| h.dig(:labels)}.compact

.compact is added only to remove nil entries. Leave off if you want to keep the same size array.

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