vishless
vishless

Reputation: 898

Parse 2d arrays in an optimal way

I need to parse the following hash of 2d arrays, where the first array has the keys and the rest of the arrays has the values.

input = {
  "result": [
    [
      "id",
      "name",
      "address"
    ],
    [
      "1",
      "Vishnu",
      "abc"
    ],
    [
      "2",
      "Arun",
      "def"
    ],
    [
      "3",
      "Arjun",
      "ghi"
    ]
  ]
}

This is the result I came up with.

input[:result].drop(1).collect{|arr| Hash[input[:result].first.zip arr]}

Here I'm iterating through the result array ignoring its first sub array (the one that contains keys) then zip the key array and value array to make a hash afterwards I collect the hash to another array.

The above solution gives me what I want which is a hash

[{"id"=>"1", "name"=>"Vishnu", "address"=>"abc"}, {"id"=>"2", "name"=>"Arun", "address"=>"def"}, {"id"=>"3", "name"=>"Arjun", "address"=>"ghi"}]

Is there a better way to achieve the same result?

Upvotes: 4

Views: 115

Answers (1)

Stefan
Stefan

Reputation: 114248

zip is the correct tool here, so your code is fine.

I'd use Ruby's array decomposition feature to extract keys and values, and to_h instead of Hash[]:

keys, *values = input[:result]
values.map { |v| keys.zip(v).to_h }

Or, if you prefer a "one-liner": (harder to understand IMO)

input[:result].yield_self { |k, *vs| vs.map { |v| k.zip(v).to_h } }

Upvotes: 6

Related Questions