Ruby,如何从两个数组创建哈希?

时间:2015-11-24 17:10:11

标签: ruby multidimensional-array hash

我是Ruby的初学者,我正在努力做到以下几点: 假设我有两个数组:

array_1 = ["NY", "SF", "NL", "SY"]
array_2 = ["apple", "banana"]

我想将数组合并到一个哈希值,因此array_1中的每个对象都将分配array_2

中的对象

提前致谢。

3 个答案:

答案 0 :(得分:6)

x = [:foo, :bar, :baz]
y = [1, 2, 3]
x.zip(y).to_h # => {:foo=>1, :bar=>2, :baz=>3}

答案 1 :(得分:2)

您可以使用zip方法,如下所示:

Hash[array_2.zip(array_1)]

答案 2 :(得分:2)

h = array_1.product([array_2]).to_h
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

我们在MRI v2.0中获得了Array#to_h。对于早期版本,请使用Kernel#Hash

h = Hash[array_1.product([array_2])]

但要注意:

array_2[0] = "cat"
array_2
  #=> ["cat", "banana"] 
h #=> {"NY"=>["cat", "banana"], "SF"=>["cat", "banana"],
  #    "NL"=>["cat", "banana"], "SY"=>["cat", "banana"]}

您可能希望:

h = array_1.each_with_object({}) { |str,h| h[str] = array_2.dup }
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

array_2[0] = "cat"
h #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}