Ruby 用索引将二维数组映射到一维数组
我有这样的2d阵列:Ruby 用索引将二维数组映射到一维数组,ruby,Ruby,我有这样的2d阵列: ary = [ ["Source", "attribute1", "attribute2"], ["db", "usage", "value"], ["import", "usage", "value"], ["webservice", "usage", "value"] ] 我想在散列中提取以下内容: {1 => "db", 2 => "import", 3 => "webservice"} // keys are indexes or
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
我知道如何通过循环二维阵列来获得这个。但既然我在学ruby,我想我可以用这样的东西
ary.each_with_index.map {|element, index| {index => element[0]}}.reduce(:merge)
这给了我:
{0=> "Source", 1 => "db", 2 => "import", 3 => "webservice"}
如何从输出映射中删除0元素?ari.drop(1)
删除第一个元素,返回其余元素
您可以使用each\u with\u 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] } ]
我会写:
Hash[ary.drop(1).map.with_index(1) { |xs, idx| [idx, xs.first] }]
#=> {1=>"db", 2=>"import", 3=>"webservice"}