I have to access the id and other important information of each operator. The structure of given data is:
{: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}]}]}
Here I am not able to access the id of each operator. All these values I have stored in instance variable @ans.
CodePudding user response:
You can do this with dig and pluck methods
@ans.dig(:items, 0, :operators)&.pluck(:id)
Or if you don't use Rails
@ans.dig(:items, 0, :operators)&.map { |el| el[:id] }
Or if you use old ruby which doesn't support safe navigation and dig
method, you can use try method:
@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"]