2013-03-20 247 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] } ]