给定这个数组(从文件生成)
["Yonkers", "DM1210", "70.00 USD"], ["Yonkers", "DM1182", "19.68 AUD"],
["Nashua", "DM1182", "58.58 AUD"], ["Scranton", "DM1210", "68.76 USD"],
["Camden", "DM1182", "54.64 USD"]]
我使用以下代码将其转换为由第二个元素(sku)索引的哈希:
result = Hash.new([])
trans_data.each do |arr|
result[arr[1]].empty? ? result[arr[1]] = [[arr[0], arr[2]]] : result[arr[1]] << [arr[0], arr[2]]
end
result
这会以我想要的格式输出哈希:
{"DM1210"=>[["Yonkers", "70.00 USD"], ["Scranton", "68.76 USD"]], "DM1182"=>[["Yonkers", "19.68 AUD"], ["Nashua", "58.58 AUD"], ["Camden", "54.64 USD"]]}
我不觉得我的代码……干净。有没有更好的方法来实现这一点?
编辑:到目前为止,我能够将其替换为:(result[arr[1]] ||= []) << [arr[0], arr[2]]
哈希没有默认值