检查存在的哈希元素并返回一个值

时间:2013-07-05 21:27:14

标签: ruby arrays hash

如果我有一个像下面的哈希数组(在JSON中),我想检查是否存在Id。

如果Id存在,那么我想返回它们存在的货币列表(可能不是Id 19的情况)。

我该怎么做?

“MyArray”:[         {             “Id”:14,             “货币”:{                 “48”:840,                 “410”:840,                 “978”:826             }         },         {             “Id”:19         }     ]

1 个答案:

答案 0 :(得分:1)

a =  [ { "Id" => 14, "Currencies" => { "48" => 840, "410" => 840, "978" => 826 } }, { "Id" => 19 } ]
h = a.detect {|i| i["Id"] == 14 && i.has_key?("Currencies") }
h["Currencies"].values unless h.nil?
# => [840, 840, 826]
相关问题