创建哈希的多维数组

时间:2014-07-27 18:03:41

标签: ruby loops hash multidimensional-array

我想循环遍历一个多维数组:

array = [[1,2,3,4,5], [6,7,8,9,10]] 

并使用另一个数组中的键创建哈希:

keyValues = "one","two","three","four","five"

我有以下代码来执行此操作:

hash = Hash.new
multiArray = Array.new
array.each do |values|
  keyValues.each do |key|
    i = keyValues.index(key)
    hash[key] = values[i]
  end
  puts hash
  multiArray << hash     
end
puts multiArray

puts hash输出:

{"one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5}
{"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}

,最后的multiArray是:

{"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}
{"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}

我无法弄清楚为什么我没有得到:

{"one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5}

为最终multiArray

3 个答案:

答案 0 :(得分:3)

既然@August已经发现了你的代码存在的问题,我想建议一种类似Ruby的紧凑方式来获得你想要的结果。

<强>代码

def make_hash(array, key_values)
    array.map { |a| key_values.zip(a).to_h }
end

示例

array = [[1,2,3,4,5], [6,7,8,9,10]] 
key_values = ["one","two","three","four","five"]

make_hash(array, key_values)
  #=> [{"one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5},
  #    {"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}]

<强>解释

Enumerable#map传递给块的第一个值是:

a = [1,2,3,4,5]

所以我们有

b = key_values.zip(a)
  #=> [["one", 1], ["two", 2], ["three", 3], ["four", 4], ["five", 5]]
b.to_h
  #=> {"one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5}

对于Ruby版本&lt; 2.0(引入Array.to_h时),我们必须写Hash(b)而不是b.to_h

类似地,传递给块的第二个值是:

a = [6,7,8,9,10]

所以

key_values.zip(a).to_h
  #=> {"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}

答案 1 :(得分:2)

您的数组有两个相同哈希对象的条目。因此,如果您在任何地方更改哈希对象,它将在两个数组条目中更改。为了避免在每个数组条目中具有相同的哈希对象,您可以在插入之前复制哈希,方法是将multiArray << hash更改为multiArray << hash.dup

答案 2 :(得分:0)

首先,安装y_support gem(gem install y_support)。它定义了Array#>>运算符,用于构造哈希:

require 'y_support/core_ext/array'
[ :a, :b, :c ] >> [ 1, 2, 3 ]
#=> {:a=>1, :b=>2, :c=>3}

有了它,你的工作就可以这样完成:

array = [1,2,3,4,5], [6,7,8,9,10] 
key_values = ["one","two","three","four","five"]

multi_array = array.map { |a| key_values >> a }
#=> [{"one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5},
     {"one"=>6, "two"=>7, "three"=>8, "four"=>9, "five"=>10}]