如何找到包含匹配值的哈希键 [英] How to find a hash key containing a matching value

查看:43
本文介绍了如何找到包含匹配值的哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有以下 clients 哈希,是否有一种快速的 ruby​​ 方式(无需编写多行脚本)来获取给定我想要匹配 client_id 的密钥?例如.如何获取client_id == "2180"的密钥?

Given I have the below clients hash, is there a quick ruby way (without having to write a multi-line script) to obtain the key given I want to match the client_id? E.g. How to get the key for client_id == "2180"?

clients = {
  "yellow"=>{"client_id"=>"2178"}, 
  "orange"=>{"client_id"=>"2180"}, 
  "red"=>{"client_id"=>"2179"}, 
  "blue"=>{"client_id"=>"2181"}
}

推荐答案

你可以使用 Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

请注意,结果将是所有匹配值的数组,其中每个值都是键和值的数组.

Note that the result will be an array of all the matching values, where each is an array of the key and value.

这篇关于如何找到包含匹配值的哈希键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆