-4

如何将数组数组(带有标题的 CSV-likes)转换为哈希数组?

headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [4,5,6], [7,8,9]...]
arr_of_arrs = headers + data

arr_of_arrs_to_structured_hash

预期输出就像

[
 {foo: 1, bar: 2, baz: 3}
 {foo: 4, bar: 5, baz: 6}
 {foo: 7, bar: 8, baz: 9}
]

编辑:对不起,我刚刚意识到我的输出不清楚。基本上数据 ara 数组的行就像在 CSV 中一样(除了我的数据不是来自 CSV)

4

1 回答 1

1
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [2,3,4]]

data.map(&headers.first.method(:zip)).map(&:to_h)
#⇒ [
#  [0] {
#    "foo" => 1
#    "bar" => 2,
#    "baz" => 3,
#  },
#  [1] {
#    "foo" => 2
#    "bar" => 3,
#    "baz" => 4,
#  }
# ]
于 2017-05-19T05:05:31.377 回答