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:
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
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"]]}
I don't feel like my code is... clean. Is there a better way of accomplishing this?
EDIT: So far I was able to replace it with: (result[arr[1]] ||= []) << [arr[0], arr[2]]
With no default value for the hash
trans_datais. And I don't know what sku means.