多维哈希轨道的访问值



我必须访问每个操作员的id和其他重要信息。给定数据的结构为:

{:items=>
[{:id=>"868f136b-ec4e-4794-a3a9-a70d4b83ab38",
:clientId=>"e92ca89f-8524-451a-9346-666d6ff39329",
:name=>"allergy_type_display",
:description=>nil,
:mnemonic=>"allergy_type_display",
:columnType=>"dropdown",
:entityId=>"d96804c4-c815-4d65-891f-b5e5c418587e",
:createdAt=>"2019-11-27T05:01:34.000Z",
:updatedAt=>"2019-11-27T05:01:34.000Z",
:display=>true,
:fallbackId=>nil,
:conceptDisplay=>false,
:businessName=>nil,
:operators=>
[{:id=>"15e8c619-7b5b-4612-b2e9-7a17112eceb9",
:mnemonic=>"gte",
:description=>"Greater than Equals to",
:createdAt=>"2019-07-01T13:10:15.000Z",
:updatedAt=>"2019-07-01T13:10:15.000Z",
:clientId=>nil},
{:id=>"38888bef-5442-4c72-b88e-44f4fd3e5614",
:mnemonic=>"eq",
:description=>"Equals To",
:createdAt=>"2019-06-26T09:30:15.000Z",
:updatedAt=>"2019-07-06T04:14:59.000Z",
:clientId=>nil},
{:id=>"4fd6ce17-10d3-42a3-8e4e-24773360db5d",
:mnemonic=>"ne",
:description=>"Not Equals To",
:createdAt=>"2019-06-26T09:19:03.000Z",
:updatedAt=>"2019-07-06T04:58:11.000Z",
:clientId=>nil},
{:id=>"b252eac5-f5dc-41ce-bc49-2364f5a73bb1",
:mnemonic=>"lte",
:description=>"Less than Equals to",
:createdAt=>"2019-07-01T13:10:15.000Z",
:updatedAt=>"2019-07-01T13:10:15.000Z",
:clientId=>nil}]}]}

这里我不能访问每个操作符的id。所有这些值都存储在实例变量@ans中.

您可以使用dig和pluck方法来完成此操作

@ans.dig(:items, 0, :operators)&.pluck(:id)

如果你不使用Rails

@ans.dig(:items, 0, :operators)&.map { |el| el[:id] }

或者如果你使用的是不支持安全导航和dig方法的旧ruby,你可以使用try方法:

@ans[:items].try(:[], 0).try(:[], :operators).try(:map) { |h| h[:id] }
# output
["15e8c619-7b5b-4612-b2e9-7a17112eceb9", "38888bef-5442-4c72-b88e-44f4fd3e5614", "4fd6ce17-10d3-42a3-8e4e-24773360db5d", "b252eac5-f5dc-41ce-bc49-2364f5a73bb1"]