How can I refactor converting this array into a Hash

来源:互联网 发布:万能数据恢复大师官网 编辑:程序博客网 时间:2024/05/22 02:11

Given this array (generated from a file)

["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"]]

I convert it to a hash indexed by the second element (the sku) with the code below:

This outputs the hash in the format I want it:

{"DM1210"=>[["Yonkers", "70.00 USD"], ["Scranton", "68.76 USD"]], "DM1182"=>[["Yonkers", "19.68 AUD"], ["Nashua", "58.58 AUD"], ["Camden", "54.64 USD"]]}
ary = [  ["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"]]hash = ary.group_by{ |a| a.slice!(1) }
arr = [["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"]]
ary.each_with_object({}){|(a, b, c), hash| (hash[b]||=[])<< [a,c]}


0 0
原创粉丝点击