目前我正在研究这个小代码。我需要使用0索引作为键,然后下一个元素需要显示为值,如下例所示:
[{"Nombre"=>"Rodrigo García", "Edad"=>13,
"Genero"=>"Masculino", "Grupo"=>"Primero", "Calificaciones"=>[9, 9, 7, 6,
8]},... #for each one of the people represented in the table
我尝试使用zip以及转置,但我不能只从一个数组中做到这一点。我将衷心感谢您的帮助。先感谢您!
table = [["Nombre","Edad","Genero","Grupo","Calificaciones"],
["Rodrigo Garcia",13,"Masculino","Primero",[9, 9, 7, 6, 8]],
["Fernanda Gonzalez",12,"Femenino","Tercero",[6, 9, 8, 6, 8]],
["Luis Perez",13,"Masculino","Primero",[8, 7, 7, 9, 8]],
["Ana Espinosa",14,"Femenino","Segundo",[9, 9, 6, 8, 8]],
["Pablo Moran",11,"Masculino","Segundo",[7, 8, 9, 9, 8]]]
p Hash[table.zip]
puts
puts
p table.transpose
答案 0 :(得分:3)
如果您打算使用大型数据集,似乎可能需要进行一些重构:
head = ["Nombre","Edad","Genero","Grupo","Calificaciones"]
table = [["Rodrigo Garcia",13,"Masculino","Primero",[9, 9, 7, 6, 8]],
["Fernanda Gonzalez",12,"Femenino","Tercero",[6, 9, 8, 6, 8]],
["Luis Perez",13,"Masculino","Primero",[8, 7, 7, 9, 8]],
["Ana Espinosa",14,"Femenino","Segundo",[9, 9, 6, 8, 8]],
["Pablo Moran",11,"Masculino","Segundo",[7, 8, 9, 9, 8]]]
ret = table.map {|row| head.zip(row) }
# or maybe better, convert to a hash, to retrieve data more easily.
ret2= table.map {|row| head.zip(row).to_h }
puts ret #=> [[["Nombre", "Rodrigo Garcia"], ["Edad", 13], ["Genero", "Masculino"]...
puts re2 #=> [{"Nombre"=>"Rodrigo Garcia", "Edad"=>13, "Genero"=>"Masculino", ...