2013-03-20 193 views
0

我有二维数组是这样的:马平二维数组与索引的一个维数组

ary = [ 
    ["Source", "attribute1", "attribute2"], 
    ["db", "usage", "value"], 
    ["import", "usage", "value"], 
    ["webservice", "usage", "value"] 
] 

我要拉出来在哈希如下:

{1 => "db", 2 => "import", 3 => "webservice"} // keys are indexes or outer 2d array 

我知道如何得到这个通过循环槽2d阵列。但是,因为我学习Ruby我以为我可以像这样的东西

ary.each_with_index.map {|element, index| {index => element[0]}}.reduce(:merge) 

做这给我:

{0=> "Source", 1 => "db", 2 => "import", 3 => "webservice"} 

我如何从我的输出图摆脱0元素?

回答

1

我会写:

Hash[ary.drop(1).map.with_index(1) { |xs, idx| [idx, xs.first] }] 
#=> {1=>"db", 2=>"import", 3=>"webservice"} 
0

ary.drop(1)删除第一个元素,返回其余元素。

你可以直接构建hash不使用each_with_object

ary.drop(1) 
    .each_with_object({}) 
    .with_index(1) { |((source,_,_),memo),i| memo[i] = source } 

合并减少或映射到元组和发送到Hash[]构造。

Hash[ ary.drop(1).map.with_index(1) { |(s,_,_),i| [i, s] } ]