将数组合并并转换为Ruby中的哈希值

时间:2012-09-01 13:34:46

标签: ruby ruby-1.9.3

Ruby中有4个数组

array1 = ["label1.1", "label1.2", "label1.3", "label1.4"]
array2 = ["data1.1", "data1.2", "data1.3", "data1.4"]

array3 = ["label2.1", "label2.2", "label2.3", "label2.4"]
array4 = ["data2.1", "data2.2", "data2.3", "data2.4"]

我需要做的是获取hash的结果数组

[ {key1=>"label1.1", value1=>"data1.1" }, 
  {key1=>"label1.2", value1=>"data1.2" },
  {key1=>"label1.3", value1=>"data1.3" },
  {key1=>"label1.4", value1=>"data1.4" },

  {key1=>"label2.1", value1=>"data2.1" },
  {key1=>"label2.2", value1=>"data2.2" },
  {key1=>"label2.3", value1=>"data2.3" },
  {key1=>"label2.4", value1=>"data2.4" }
]

你的想法?

2 个答案:

答案 0 :(得分:3)

(array1 + array3).zip(array2 + array4).map {|k, v| { key1: k, value1: v } }

答案 1 :(得分:2)

不能比这更简单和更短:

your_hash = Hash[(array1 + array3).zip(array2 + array4)]

给你:

=> {"label1.1"=>"data1.1", "label1.2"=>"data1.2", "label1.3"=>"data1.3", "label1.4"=>"data1.4", "label2.1"=>"data2.1", "label2.2"=>"data2.2", "label2.3"=>"data2.3", "label2.4"=>"data2.4"}