将内部数组转换为Hash

时间:2018-03-08 06:43:27

标签: ruby

我有以下数组

a=[["name","age"],
      ["Raja","29"],
      ["Gop","30"]
      ["pal","21"]
      ]

我需要以下Hash

a=[{"name"=>"Raja","age"=>"29"},{"name"=>"Gop","age"=>"30"},{"name"=>"Gop","age"=>"30"},{"name"=>"pal","age"=>"21"}]

它的作用是,它取第一行的键,它使用数组的其余部分作为我上面显示的值。

我编写了以下代码并且工作正常。

 myArray = myArray.transpose unless columnHeaders
    arrayHash = []
    (1..myArray.length - 1).each do |i|
      rowHash = OrderedHash.new
      (0..myArray[i].length - 1).each do |j|
        rowHash[myArray[0][j]] = myArray[i][j]
      end
      arrayHash << rowHash
    end
    return arrayHash

但我觉得上面的代码不属于Ruby编码风格,有没有什么方法可以在Ruby风格中编写更好的代码?你能帮我写ruby惯用代码吗?

2 个答案:

答案 0 :(得分:4)

我会做这样的事情:

a = [['name', 'age'], ['Raja', '29'], ['Gop', '30'], ['pal', '21']]
a[1..-1].map { |element| a[0].zip(element).to_h }
#=> [
#     { "name" => "Raja", "age" => "29" },
#     { "name" => "Gop", "age" => "30" },
#     { "name" => "pal","age" => "21" }
#   ]

答案 1 :(得分:2)

使用Array#productArray#transpose

a = [['name','age'], ['Raja','29'], ['Gop','30'], ['pal','21']]
[a[0]].product(a[1..-1]).map(&:transpose).map(&:to_h)
#⇒ [{"name"=>"Raja", "age"=>"29"},
#   {"name"=>"Gop", "age"=>"30"},
#   {"name"=>"pal", "age"=>"21"}]