tnaught
tnaught

Reputation: 301

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=>"**%*%"}}
]

Upvotes: 0

Views: 1003

Answers (1)

whodini9
whodini9

Reputation: 1434

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.

Upvotes: 1

Related Questions