简体   繁体   English

遍历数组或哈希值以查找Ruby中的密钥

[英]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. 我正在尝试访问键: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. 在Ruby 2.3+中,您可以使用Hash#dig返回嵌套键或nil的值。

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

.compact is added only to remove nil entries. 添加.compact仅用于删除nil条目。 Leave off if you want to keep the same size array. 如果要保留相同大小的数组,请不要使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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