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
- How can I refactor converting this array into a Hash
- How can I put a ListView into a ScrollView without it collapsing?
- How can I insert a checkbox into the header of my view?
- How can I remove this user
- How do I sort an array of hashes by a value in the hash?
- How can I combine elements of an array that have a common element?
- 009:How can I test if an array contains a certain value?
- How can I create a tray icon
- How can I create a tray icon
- How can I flip a UIImageView?
- How can I print a JavaScript object?
- How to: Load Unmanaged Resources into a Byte Array
- How to group anagrams in a string into an array
- How can I create a object for a note?
- How can I start a VM without getting a window?
- how can i get [5, 7, 13, 2] to go to [5*0, 7*1, 13*2, 2*3] then get the sum of this array.
- can’t refactor code used in this language
- Powershell: Read in file without converting into string array
- 重定向和转发的区别【转】
- 黑马程序员--类加载器
- linux内核学习----系统调用
- C# 3.0 入门系列(一)
- 企业级PAAS平台-多租户
- How can I refactor converting this array into a Hash
- USB枚举详细过程剖析
- wait系列函数
- 关于webview调用js出现has no method 'toString'
- 终端/控制台设置颜色字体、光标定位和清屏
- python 获得github代码库列表
- 从面试官的视角来提升面试者的必须具备的IT技能
- servlet应用案例
- 利用DHT网络原理制作bt采集蜘蛛