我很难弄清楚如何使用第一行中的键使下一行成为哈希.
我有一个像这样结构的数组:
[["id", "name", "address"], [1, "James", "...."], [2, "John", "...."] ]
成为:
[{ id : 1, name: "James", address: "..."}, ...]
我使用了一个gem"simple_xlsx_reader",我只提取出第一张.
wb.sheets.first.row
从上面得到一个类似的数组输出.
谢谢!
arr = [["id", "name"], [1, "Jack"], [2, "Jill"]] [arr.first].product(arr.drop 1).map { |a| a.transpose.to_h } #=> [{"id"=>1, "name"=>"Jack"}, {"id"=>2, "name"=>"Jill"}]
步骤:
b = [arr.first] #=> [["id", "name"]] c = arr.drop 1 #=> [[1, "Jack"], [2, "Jill"]] d = b.product(c) #=> [[["id", "name"], [1, "Jack"]], [["id", "name"], [2, "Jill"]]] d.map { |a| a.transpose.to_h } #=> [{"id"=>1, "name"=>"Jack"}, {"id"=>2, "name"=>"Jill"}]
d
传递给map
块的第一个元素是:
a = d.first [["id", "name"], [1, "Jack"]]
因此块计算是:
e = a.transpose #=> [["id", 1], ["name", "Jack"]] e.to_h #=> {"id"=>1, "name"=>"Jack"}